call: 改变当前执行上下文的this指针
function dog(color){ this.color = color; } dog.prototype.eat = function(){ return this.color+ " dog can eat food"; } var blackDog = new dog(‘black‘); blackDog.eat();// black dog can eat food var redDog = { color: "red" } blackDog.eat.call(redDog);//red dog can eat food
总结: 一开始blackDog 对象中的this只向其本身,所以this.color就是实例化对象时传入的black, 然而当执行blackDog.eat.call(redDog)这个方法时,通过call方法改变了this的指向,this 指向redDog, 所以this.color就是red。
apply: 和call方法大致相同,改变当前执行上下文的this指针,但是传入的参数(第一个以外)是一个数组。
function dog(color){ this.color = color; } dog.prototype.showSkills= function(eat, run, jump){ console.log(this.color + " dog skill: " + eat +"," + run +","+ jump); } var blackDog = new dog(‘black‘); var redDog = { color: "red" } blackDog.showSkills.call(redDog, "eat", "run", "jump");//red dog skill: eat,run,jump blackDog.showSkills.apply(redDog, ["eat", "run", "jump"]);//red dog skill: eat,run,jump
总结: 由此可见,call和apply用法大致相同,但是apply的在调用另一个方法是,传入的多个参数是数据,数组内的多个参数会以原有的顺序对应到每一接受器上。
bind: 功能与call和apply相似 其作用是改变某个方法的this指针,并且在该方法被调用时才会生效,而不像call和apply会理解执行
eg1: function bindDemo(){ console.log(this.a) }; bindDemo.bind({a: "i am this.a"}) //此处并没有被掉用,只是一个声明 bindDemo.bind({a: "i am this.a"})();// i am this.a eg2: function cat(){ this.eat = function(){ console.log(this.name + " cat is eating"); } } var Cat = new cat(); Cat.eat.call({name: "blackCat"});// blackCat cat is eating Cat.eat.apply({name: "redCat"});// redCat cat is eating Cat.eat.bind({name: "otherCat"}); //此处只会返回一个对象,不会有输出,因为还没有真正调用 Cat.eat.bind({name: "otherCat"})();//otherCat cat is eating
总结: bind方法再被使用时,必须进行掉用才会执行,而call 和apply 则会直接掉用原来的方法,并改变this指针。
时间: 2024-11-08 12:09:45