JavaScript中函数调用的方式
-
作为普通函数调用
function foo(){
console.log("作为普通函数调用");
}
foo() -
作为对象方法调用
var o = {
foo: function(){
console.log("作为对象方法调用");
}
}
o.foo()
-
作为构造函数调用
function Foo(){
this.bar = "作为构造函数调用";
}
var o = new Foo();
console.log(o.bar); //作为构造函数调用
-
使用call、apply调用
function foo(){
console.log(this.a);
}
var a = "作为普通函数调用";
foo(); //作为普通函数调用
var o1 = Object.create(null);
var o2 = Object.create(null);
o1.a = "使用call调用";
o2.a = "使用apply调用";
foo.call(o1); //使用call调用
foo.apply(o2); //使用apply调用call、apply的作用是一样的——将函数的执行上下文(this)绑定到第一个参数上,区别在于call可以将原函数的其他参数直接传入,而apply则是以数组的形式传入。
//这里不做任何校验
function foo(a, b){
return this.number + a + b;
}
var o = {
number: 2
}
foo.call(o, 2, 2); //6
foo.apply(o, [2,2]); //6