1、改变this
A:call()方法:
function sayNameForAll(label){ console.info(label + ":" + this.name); } var person1 = { name : "Nicholas" }; var person2 = { name = "Greg" }; var name = "Michale"; sayNameForAll.call(this,"global"); //outputs “global:Michale” sayNameForAll.call(person1,"person1"); //outputs "person1:Nicholas" sayNameForAll.call(person2,"person2"); //outputs "person2:Greg"
B:apply()方法:和call()方法一样,接受两个参数,this的值和一个数组或者类似数组的对象,内含需要被传入函数的参数,不需要像使用call()那样一个个指定参数
function sayNameForAll(label){ console.info(label + ":" + this.name); } var person1 = { name : "Nicholas" }; var person2 = { name = "Greg" }; var name = "Michale"; sayNameForAll.apply(this,["global"]); //outputs “global:Michale” sayNameForAll.apply(person1,["person1"]); //outputs "person1:Nicholas" sayNameForAll.apply(person2,["person2"]); //outputs "person2:Greg"