es6(bind)

参考资料

The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value. A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g. by using that method in callback-based code). Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:

this.x = 9;    // this refers to global "window" object here in the browser
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var retrieveX = module.getX;
retrieveX();   
// returns 9 - The function gets invoked at the global scope

// Create a new function with 'this' bound to module
// New programmers might confuse the
// global var x with module's property x
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 12月6日,我校后勤服务部厨房工作会议在小学部三楼会议室召开,本次会议主要从学生生长发育特点出发,就讲究营养...
    清浅光阴阅读 1,031评论 0 0
  • 今天天气凉爽有很多美好发生,也觉得自己做了好多事情! 1.今天去给好友爸爸过生日,精心为他准备了干果,去了之后得之...
    王玉文ts阅读 195评论 3 0
  • 说到互联网的未来,兴奋莫名,又忧心忡忡,天使的面孔,魔鬼的身材;火焰在海水上燃烧……个中滋味与纠结,谁又说得清?!...
    camer阅读 383评论 0 0
  • 海报设计 尺寸:2*2.5 一个就行,我们有2米x2.5米的板子,海报贴上去就行 包含元素: 1. 顶部氛围图,需...
    林昱苏河阅读 265评论 0 1

友情链接更多精彩内容