【问题标题】:JqueryInAction Book Example Uses Local Variable Instead of thisJqueryInAction 书籍示例使用局部变量而不是 this
【发布时间】:2018-04-22 17:26:26
【问题描述】:

我是 Jquery 的新手,正在阅读“JQueryInAction”一书。 我从这本书中看到了这个例子:

$(function(){
    $('*').each(function(){
        var current = this;
        this. onclick = function(event) {
            if (!event) event = window.event;
            var target = (event.target) ? event.target : event.srcElement;
            say('For ' + current.tagName + '#'+ current.id +
                ' target is ' + target.id);
        }
    });
});

这里我真的不明白在第 3 行使用局部变量 current 而不是 this

注意:我了解 JavaScript 并且了解 closures 以及 this 如何在 closure 中不可用但这里不是这样,this 在事件处理程序中可用。 这里current有什么意义。

【问题讨论】:

    标签: javascript jquery function closures


    【解决方案1】:

    在引入 ES6 箭头函数之前,所有函数都有自己的this,其值取决于函数的调用方式。

    这里的事件处理程序有自己的this,但也需要访问其封闭词法上下文的this,但显然不能同时使用this。为了解决这个问题,外部函数中this 的值被保存到一个新变量中,这样它就可以在处理程序中使用而不会出现问题。

    ES6 Arrow functions没有自己的thisarguments;而是使用封闭执行上下文的 this 值。

    你的代码可以改写为:

    $('*').each(function() {
      this.onclick = (event) => {
        if (!event) event = window.event;
        var target = (event.target) ? event.target : event.srcElement;
        say('For ' + this.tagName + '#'+ this.id + ' target is ' + target.id);
      }
    });
    

    【讨论】:

    • 内部的 this 和外部环境的 this 不一样,因为事件处理程序是在外部词法环境的 this 上调用的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多