js的函数调用会有两个额外的参数:this和arguments。(arguments是参数组,并非真实的数组,但可以使用.length方法获得长度)
js的4种调用模式:
1.方法调用模式
2.函数调用模式
3.构造器调用模式
4.apply调用模式
详解如下:
1.方法调用模式1
2
3
4
5
6
7var myobject={
value:0,
inc:function(){
alert(this.value)
}
}
myobject.inc();
2.函数调用模式1
2
3
4
5
6var add=function(a,b){
alert(this);//this被绑定到window
return a+b;
}
var sum=add(3,4);
alert(sum);
备注:普通函数的调用this指向全局变量
普通的函数调用:1
2function a(){}
a();
等价于匿名函数:1
2
3(function()}{
})()
3.构造器调用模式(不使用)1
2
3
4
5function Persion(name,age){
this.name = name;//this指向所调用的对象
this.age = age;
}
var obj = new Person('Singapo91',88);
4.apply调用模式1
2
3
4
5
6var add=function(a,b){
return a+b;
}
var arr=[10,20];
var sum=add.apply(this,arr);//this指针所指向的对象
alert(sum);
最新访客: