javascript的call、apply和bind[stackoverflow]

They all attach this into function (or object) and the difference is in the function invocation (see below).
call attaches this into function and executes the function immediately:

var person = {  
  name: "James Smith",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

person.hello.call(person, "world"); // output: "James Smith says hello world"

bind attaches this into function and it needs to be invoked separately like this:

var person = {  
  name: "James Smith",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

var helloFunc = person.hello.bind(person);
helloFunc("world");  // output: "James Smith says hello world"

or like this:

...    
var helloFunc = person.hello.bind(person, "world");
helloFunc();  // output: "James Smith says hello world"

apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:

function personContainer() {
  var person = {  
     name: "James Smith",
     hello: function() {
       console.log(this.name + " says hello " + arguments[1]);
     }
  }
  person.hello.apply(person, arguments);
}
personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"                         

shareeditflag

edited Apr 28 at 7:52

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 我真希望 世界上有一種咒語 我一念你就能出現 我不知道 你的襯衫上有沒有陽光的味道 我只知道 想你的時候空氣里都是...
    木易小閱讀 246評論 0 0
  • 夢境其實就是自己內心最真實的想法! 有沒有那么一個人,你認為可以是一身摯友,最后還是需要考慮! 快畢業了,拖著疲憊...
    CapricornusN閱讀 300評論 0 0
  • 文、M。 繁華落盡的黃昏,枝椏停滿了思念,這轉眼即逝的時光,最后究竟剩下了什么。 時間淘盡了所有,朋友還是收獲,得...
    Anni愛夏閱讀 153評論 0 0
  • 在孩子出生的那一刻,你覺得你是世界上最幸福的人,你愛的人,愛你的人都圍在你身邊對你祝賀,你有兒子了。你覺得...
    舉步踏輕塵閱讀 229評論 0 1