JS函数调用的四种方法:方法调用模式,函数调用模式,构造器调用模式,apply,call调用模式
1.方法调用模式:
先定义一个对象,然后在对象的属性中定义方法,通过myobject.property来执行方法,this即指当前的myobject
对象。
var blogInfo={
blogId:123,
blogName:"werwr",
showBlog:function(){alert(this.blogId)}
}
blogInfo.showBlog()
2.函数调用模式
定义一个函数,设置一个变量名保存函数,这时this指向到window对象。
var myfunc = function(a,b){
return a+b
}
alert(myfunc(3,4))
3.构造器调用模式
定义一个函数对象,在对象中定义属性,在其原型对象中定义方法。在使用prototype的方法时,必须实例化该对象才能调用其方法。
var myfunc = function(a){
this.a = a
}
myfunc.prototype = {
show:function(){alert(this.a)}
}
var newfunc = new myfunc("123123123")
newfunc.show()
4.apply,call调用模式
var myobject={}
var sum = function(a,b){
return a+b
}
var sum2 = sum.call(myobject,10,30)//var sum2 = sum.apply(myobject,[10,30])
alert(sum2)
JS函数的参数在function内可以用arguments对象来获取。参数的调用有两种方式:
1、期望参数的使用。
2、实际传递参数的使用。
应用举例:
function
Test(a,
b){
var
i,
s
=
"Test函数有"
var
numargs
=
arguments.length
//
获取实际被传递参数的数值。
var
expargs
=
Test.length
//
获取期望参数的数值,函数定义时的预期参数个数(有a和b
2个参数)。
s
+=
(expargs
+
"个参数。")
s
+=
"\n\n"
for
(i
=0
i
<
numargs
i++){
//
获取参数内容。
s
+=
"
第"
+
i
+
"个参数是:"
+
arguments[i]
+
"\n"
}
return(s)
//
返回参数列表。
}
alert(Test('param1','second
param','第三个参数'))
需要注意的是:
arguments是一个object对象,它不是数组,不能对它使用shift、push、join等方法。
上述举例时用的arguments[i]中的i只是作为arguments对象的属性,并不能理解为数组下标。
代码演示
<html>
<head>
<script
language="javascript">
function
reloadList(){
if(typeof
arguments[0]
==
"function"){
arguments[0].call(this)
arguments[0]()
}
if(typeof
arguments[0]
==
"string")
alert(arguments[0])
if(typeof
arguments[0]
==
"number")
alert(arguments[0])
if(typeof
arguments[0]
==
"undefined")
alert(arguments[0])
if(typeof
arguments[0]
==
"boolean")
alert(arguments[0])
if(typeof
arguments[0]
==
"null")
alert(arguments[0])
}
reloadList(function(){})
</script>
</head>
<body>
</body>
以上这篇深入理解JS函数的参数(arguments)的使用就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。