call()、apply()的第一个实参是函数调用的上下文,在函数体内通过this来获得对它的引用。
call()将实参用逗号分隔;apply ()将实参放入数组、类数组对象中。
function hello(roleA,roleB){
console.log(this.name,roleA,roleB);
}
var turtles = {
name : '忍着神龟'
};
hello.call(turtles,'Leo','Raph');
hello.apply(turtles,['Mikey','Don']);
bind()是ECMAScript5中新增的方法,主要作用就是将函数f绑定至某个对象o。这个方法会返回一个新的函数g,调用新的函数g会把原始的函数f当作o的方法来调用。
var saints = {
name : '圣斗士星矢'
};
var hello2 = hello.bind(saints);
hello2('Mu','kanon');
var hello3 = hello.bind(saints,'Aioria');
hello3('Shaka');