標籤:
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 foodvar 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,jumpblackDog.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.aeg2:function cat(){ this.eat = function(){ console.log(this.name + " cat is eating"); } }var Cat = new cat();Cat.eat.call({name: "blackCat"});// blackCat cat is eatingCat.eat.apply({name: "redCat"});// redCat cat is eatingCat.eat.bind({name: "otherCat"}); //此處只會返回一個對象,不會有輸出,因為還沒有真正調用Cat.eat.bind({name: "otherCat"})();//otherCat cat is eating
總結: bind方法再被使用時,必須進行掉用才會執行,而call 和apply 則會直接掉用原來的方法,並改變this指標。
學些js call apply bind的新的收穫,做個記錄,希望大家多多指導