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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 我真希望 世界上有一种咒语 我一念你就能出现 我不知道 你的衬衫上有没有阳光的味道 我只知道 想你的时候空气里都是...
    木易小阅读 271评论 0 0
  • 梦境其实就是自己内心最真实的想法! 有没有那么一个人,你认为可以是一身挚友,最后还是需要考虑! 快毕业了,拖着疲惫...
    CapricornusN阅读 395评论 0 0
  • 文、M。 繁华落尽的黄昏,枝桠停满了思念,这转眼即逝的时光,最后究竟剩下了什么。 时间淘尽了所有,朋友还是收获,得...
    Anni爱夏阅读 177评论 0 0
  • 在孩子出生的那一刻,你觉得你是世界上最幸福的人,你爱的人,爱你的人都围在你身边对你祝贺,你有儿子了。你觉得...
    举步踏轻尘阅读 280评论 0 1

友情链接更多精彩内容