简体   繁体   English

带有初始化的JavaScript阴影

[英]JavaScript shadowing with initialization

Before I dive into the question I want to clarify that my use case involves patching a trans-compiler to generate a proper equivalent, hence the somewhat awkward question. 在深入探讨这个问题之前,我想澄清一下我的用例涉及修补反编译器以生成适当的等效项,因此这个问题有些尴尬。

I want to shadow an outside variable but initialize it to the same value as outside as well. 我想隐藏一个外部变量,但也将其初始化为与外部相同的值。 Here is an example: 这是一个例子:

var a = 2;
(function(){
    var a = a;
    a += 3;
    // I want `a` to be 5
})();
// I want `a` to be 2

I realize with the above example the internal a will be NaN ( undefined + 3 ), but can I initialize the variable doing the shadowing to the same one that it shadows somehow? 通过上面的示例,我意识到内部a将为NaNundefined + 3 ),但是我可以将进行阴影处理的变量初始化为以某种方式阴影的变量吗? Passing it as an argument is not an option as that function will be written by the user, the only thing that will be consistent is the presence of inner scope. 不能将其作为参数传递,因为该函数将由用户编写,唯一一致的是内部作用域的存在。 I was thinking of changing the name of internal variable a but the compiler isn't currently built in a way to track it easily and this would introduce additional headaches. 我当时正在考虑更改内部变量a的名称,但是编译器当前并未以易于跟踪的方式构建,这会带来更多的麻烦。

You need to pass a as parameter in your IIFE . 您需要在IIFE中传递a as参数。

(function(parameter){
 // «parameter» contains the given value.
 // parameter = "Some value".
})("Some value");

Something like this: 像这样:

 var a = 2; // Variable declaration in the global scope. (function(a) { a += 3; // I want `a` to be 5 console.log(a); // Prints the current value in the local scope. })(a); // The parameter: var a = 2; console.info(a); // Prints the current value in the global scope. // I want `a` to be 2 

Since that is a immediately invoked function expression it has a completely different scope than the code written outside of it. 由于那是立即调用的函数表达式,因此它的作用域与在其外部编写的代码完全不同。 There's no way to do what you are asking without passing in an argument in some way (whether directly when executing or using bind), or changing the function so the scope is that of the scope where the wanted var a is defined. 没有某种方式(无论是直接在执行或使用bind时)传递参数,还是更改函数,就无法执行您要问的事情,因此作用域就是定义了所需var a的作用域。

With that being said perhaps you can return some methods that will set a to the appropriate value. 话虽如此,也许您可​​以返回一些将a设置为适当值的方法。

http://jsbin.com/vazequhigo/edit?js,console http://jsbin.com/vazequhigo/edit?js,console

var a = 2;
w = (function(){
    var setA = function(val) {
        a = val;
    }
    var addA = function(val) {
        a += val;
        return a;
    }

    var a = 0;

    return {
        setA: setA,
        addA: addA,
    };
})();

w.setA(a);
console.log(w.addA(3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM