这三个方法都改变了函数作用域,也就是改变了函数体内this指代的对象。
call和apply
这两个方法只是传递参数有区别,作用完全一样,直接上代码说明:
var Rabbit = function(){
this.name = "rabbit";
this.age = 3;
this.introduce = function(msg, msg2){
console.log("my name is " + this.name + ",age is " + this.age);
console.log(msg);
console.log(msg2);
}
}
var rabbit = new Rabbit();
rabbit.introduce("zhizhi", "jiji");
var Monkey = function(){
this.name = "monkey";
}
var monkey = new Monkey();
//这两个函数的第一个参数都是替代者,以下代码的意思是把猴子当兔子调用兔子的方法
//实际上也就是改变了introduce方法中的this,把this指代的对象由rabbit换成monkey
//不同的是,原函数中的参数列表,call中是逐个传递,apply中则要写成数组形式
rabbit.introduce.call(monkey,"aaaa", "bbbb");
rabbit.introduce.apply(monkey,["aaaa", "bbbb"]);
程序执行结果如下图,符合预期
![](https://img.haomeiwen.com/i5544814/cf6689207de67c4a.png)
bind
bind方法改变作用域后会生成新的函数,测试代码如下:
var introduce = rabbit.introduce.bind(monkey);
introduce("xxxx", "yyyy");
//结果是function,bind函数会生成新的函数
console.log(typeof(introduce))
//结果是false,新的函数跟原来的不同
console.log(rabbit.introduce == introduce)
网友评论