English 中文(简体)
查阅 j印匿名方法中的ger印分类变量
原标题:Access a copied integer variable in javascript anonymous method

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]();
}

我预计第1个<代码>funcArray(>)呼吁说0,第2个指1。 但是,这两者都说1。 如何做到这一点?

作者: 我确保我制作一份可变的<代码>i。 然后,在每次同时举行的活动中,我都设立了一个全新的职能点。 每个职能都提及其自己的<代码>i,即contextCopy。 但是,由于某种原因,这两项职能都提到了相同的<条码>contextCopy-variable。

这一工作如何用javascript?

最佳回答

贾瓦伦古文有条不紊的关闭。 即便是你在分配一席工作时,也考虑进去。 表格,背景 拷贝本身是禁试(与C#不同,{}给你新的范围块)。 为此:

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

Java文中的弹片({})没有像C#中那样包含变数。

只有关闭(功能)才带来新的范围,并包含变量。

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

实际解释为:

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

为了获得变数的复印件,你需要总结一下该代码,并结束:

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

你们不会产生一个变数的复印件。 相反,你使这种不同的GC-赖以决定其用途的关闭。 这意味着,在休息期间,一变量继续生活在最后状态(1)中,而两处都提到了封闭状态。

采用另一种方式:在变数上封闭不会将其复制到您的关闭中(对物体而言可能没有什么意义),它只是将你的关闭作为变量,并确保这种变数不会在封闭之前排出。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签