栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript回调范围

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript回调范围

(提取了一些其他答案的注释中隐藏的解释)

问题在于以下几行:

this.dom.addEventListener("click", self.onclick, false);

在这里,您传递了一个函数对象用作回调。当事件触发时,该函数被调用,但是现在它与任何对象(this)都没有关联。

可以通过将函数(及其对象引用)包装在闭包中来解决此问题,如下所示:

this.dom.addEventListener(  "click",  function(event) {self.onclick(event)},  false);

由于在创建闭包时为变量self分配了 值,因此闭包函数将在以后调用self变量时记住它的值。

解决此问题的另一种方法是制作一个实用函数(并避免使用变量绑定 this ):

function bind(scope, fn) {    return function () {        fn.apply(scope, arguments);    };}

更新后的代码将如下所示:

this.dom.addEventListener("click", bind(this, this.onclick), false);

Function.prototype.bind
是ECMAscript5的一部分,并提供相同的功能。因此,您可以执行以下操作:

this.dom.addEventListener("click", this.onclick.bind(this), false);

对于尚不支持ES5的浏览器,MDN提供以下填充程序:

if (!Function.prototype.bind) {    Function.prototype.bind = function (oThis) {      if (typeof this !== "function") {        // closest thing possible to the ECMAscript 5 internal IsCallable function        throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");      }    var aArgs = Array.prototype.slice.call(arguments, 1),fToBind = this,fNOP = function () {},          fBound = function () { return fToBind.apply(this instanceof fNOP  ? this  : oThis || window,aArgs.concat(Array.prototype.slice.call(arguments)));          };    fNOP.prototype = this.prototype;      fBound.prototype = new fNOP();    return fBound;    };  }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/575138.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号