“这个”怎么样?工作关​​闭? [英] How does 'this" work in closure?

查看:45
本文介绍了“这个”怎么样?工作关​​闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得这份文件说这里有一个关闭:

I got to this document which says there is a closure happening here:

function addHandler(){
    document.getElementById('el').onclick = function(){
        this.style.backgroundColor = 'red';
    };
}

虽然此代码删除了闭包:

While this code removes the closure:

function addHandler() {
    var clickHandler = function() {
        this.style.backgroundColor = 'red';
    };
    (function() {
        var el = document.getElementById('el');
        el.onclick = clickHandler;
    })();
}

我看不出第二个如何解决关闭问题。为什么 el.onclick = clickHandler 的代码不能创建一个闭包? clickHandler 必须使用 el 来实现。

I can't see how the second one solves the closure issue. Why would not the code at el.onclick = clickHandler create a closure? clickHandler's this has to be fulfilled with el.

推荐答案

您的示例不正确。您链接的文档指出此代码块会创建一个可能泄漏内存的闭包(请注意外部函数中的变量):

Your example is not correct. The document you have linked to states that this code block creates a closure which may leak memory (note the variable in the outer function):

function addHandler() {
    var el = document.getElementById('el');
    el.onclick = function() {
        this.style.backgroundColor = 'red';
    };
}

您发布的两个示例都没有创建闭包(或只是空闭包)但是他们使用不同的方法来避免它。

Both examples you posted do not create a closure (or only an empty one), but they use different means to avoid it.

另请注意,这个问题似乎只会影响IE的JS引擎。其他引擎,如V8 / Chrome,似乎只捕获闭包中内部函数中使用的变量,所以我希望在这个代码示例中不会创建循环引用,即使它们应该能够使用循环引用处理垃圾收集。

Also note that this problem seems to affect IE's JS engine only. Other engines, auch as V8 / Chrome, seem to only capture the variables used in inner functions in closures, so that I'd expect that no circular reference would be created in this code example, and even if it would they should be able to handle the garbage collection with the circular reference.

这篇关于“这个”怎么样?工作关​​闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆