在JS中,函数只定义一次,但是可能被执行或调用任意次数。我们知道,函数的调用主要有四种方法:
1,方法调用模式
2,函数调用模式
3,构造函数调用模式
4,apply或call调用模式
1,方法调用
var object={ color : ”蓝色“, say:function(){ console.log(this.color) } } object.say()//在say方法中,this指向方法中的对象
2,函数调用
var add=function(a,b){ console.log(this)//this指向window(全局) return a+b; } var sum=add(3,4); console.log(sum);//7
3,构造函数调用模式
function Robot(name){ this.name= name;//this指向新生成的实例 this.say=function(){ console.log(this.name) } } var new_name = new Robot('alan'); robot_1.say() // 打印结果为'alan',this指向alan var new_names = new Robot('adam'); robot_2.say() // 打印结果为'adam',this指向adam
4,apply或call调用模式
若不考虑函数内的this引用的话,对函数调用apply或call方法和类似于 say() 这样的普通调用方式是一样的
例
var robot_1 ={ name:"cup", say:function(){ console.log(this.name) } }; var robot_2 ={ name:"bower" }; robot_1.say.apply(robot_2) //打印结果为bower,通过apply调用robot_1.say方法.方法内的this引用引用了robot_2 robot_1.say.call(robot_2) //打印结果为bower,通过call调用robot_1.say方法.方法内的this引用引用了robot_2
apply和call能够强制函数内的this指定某一对象,他们传递的第一个参数没什么不同,但不同的是剩余参数的传递方式。剩下的参数对于apply方法来讲是将参数组合为数组传入,而call方法则原样传递。
例如
function say(sex,age) { console.log("My name is " + this.name + ",I'm a " + age + "years old " + sex + ".") } say.apply({name:"cup"}, [12, "boy"]) // 从第二个参数起,用数组来传参. say.call({name:"cup"}, 12, "boy") // 从第二个参数起,参数原样传递.