闭包中局部变量的错误行为 [英] Erroneous behavior of local variables in closures

查看:81
本文介绍了闭包中局部变量的错误行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在以下代码中.首先,我将描述用例:被ColorGradient的实例调用.调用 this.listController.addItem(...)时,提供了名为 onSelect 的回调函数,每次触发listController-item的onSelect事件时都会调用该函数.我想做的是将对 GLab.ColorSlider.applyColorGradient(...)的调用包装到一个新的闭包中,以便分配给 addPreset的"cg"值参数" *将被捕获",在里面.但这不起作用.

I am stuck at the following code. At first I'll describe the use-case: The function "addPreset" gets called with an instance of ColorGradient. When calling this.listController.addItem(...) a callback function named onSelect ist supplied, which gets called everytime the onSelect-event on the listController-item is triggered. What I wanted to do is wrapping the call to GLab.ColorSlider.applyColorGradient(...) into a new closure, so that the assigned value of addPreset's "cg" argument"* will be "caught" inside it. But it doesn't work.

问题:现在,每次调用 addPreset 时, cg 的值(随调用传递)将覆盖之前错误分配的所有值.但是, this.presetList 始终保持正确的值(我希望这些值会在闭包函数中捕获.即使插入匿名函数来破坏范围也无济于事.

PROBLEM: Now everytime addPreset is called, the value of cg (being passed with a call) will override all values that bad been assigned before. However, this.presetList holds always correct values (the ones I expected to be caught inside the closure-function. Even inserting an anonymous function for breaking the scope doesn't help.

请帮助我.:-)

到目前为止,谢谢

function addPreset(cg) {
    if (!(cg instanceof ColorGradient)) {
        throw new TypeError("PresetManager: Cannot add preset; invalid arguments received");
    }

    var newIndex = this.listController.addItem(cg.getName(), {
        onSelect: (function(cg2) {
            return function() {
                // addPreset's scope should now be broken
                GLab.ColorSlider.applyColorGradient(cg2);
                console.log(cg2);
            }
        })(cg)
    });

    this.presetList[newIndex] = cg;
}

@bobince:当然可以.

@bobince: of course you can.

上面的代码段是 PresetManager.js 的一部分,而listController是类 ListWrapper.js

the code snippet above is part of PresetManager.js and the listController is an instance of the class ListWrapper.js

http://code.assembla.com/kpg/subversion/nodes/GradientLab/lib-js/PresetManager.js http://code.assembla.com/kpg/subversion/nodes/GradientLab/lib-js/ListWrapper.js

@Matt: cg是ColorGradient的实例.我的自定义类.此外,可以确保总是有效"的.值作为cg传递.(如果您有几分钟的时间,可以zip存档的形式下载整个assembla仓库.在启用Firebug控制台的情况下,在FF> 3.5中解压缩并进行测试.)

@Matt: cg is an instance of ColorGradient. A custom class of myself. Further more, it is assured, that always "valid" values are passed in as cg. (When you'd have a few minutes you can download the whole assembla repo as zip-archive. Unzip and test in FF > 3.5 with Firebug console enabled.)

推荐答案

可以在以下问题中找到答案:

Answer can be found in this question: Doesn't JavaScript support closures with local variables?

这篇关于闭包中局部变量的错误行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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