本文介绍了在javascript匿名方法中访问复制的整数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个C#开发人员,习惯了闭包在C#中工作的方式。
目前我必须使用匿名javascript函数,并遇到以下代码片段的问题:

I am a C# developer and used to the way closures work in C#. Currently I have to work with anonymous javascript functions and experience a problem with the following snippet:

    function ClosureTest() {
    var funcArray = new Array();

    var i = 0;
    while (i < 2) {
        var contextCopy = i;

        funcArray[i] = function() { alert(contextCopy); return false; };

        i++;
    }

    funcArray[0]();
    funcArray[1]();
}



我希望第一个 funcArray c $ c>调用 0 ,第二个说 1 。但是,他们都说 1

I expect the first funcArray() call to say 0 and the second to say 1. However, they both say 1. How is that possible?

通过写 var contextCopy = i 我确保我创建了一个 i -variable。然后,在每个while-iteration中,我创建一个全新的函数指针。每个函数引用其自己的 i 副本,即 contextCopy 。但是,由于某些原因创建的函数指的是相同的 contextCopy -variable。

By writing var contextCopy = i I make sure that I create a copy of the i-variable. Then, in each while-iteration I create a completely new function pointer. Each function refers to its own copy of i, which is contextCopy. However, both created functions for some reason refer to the same contextCopy-variable.

推荐答案

JavaScript具有词法闭包,而不是闭包。即使您将i分配给contextCopy,contextCopy本身也是ClosureTest的一个词汇成员(它与C#不同,其中{}为您提供了一个新的范围块)。尝试这样:

JavaScript has lexical closures, not block closures. Even though you are assigning i to contextCopy, contextCopy is, itself, a lexical member of ClosureTest (which is different from C#, where the {} give you a new scoped block). Try this:

while (i < 2) {
    funcArray[i] = (function(value) { 
        return function(){ alert(value); return false; }
    })(i);
    i++;
}

这篇关于在javascript匿名方法中访问复制的整数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 06:35