2016-11-26 91 views
0

全局变量被认为是不好的做法,但我想用它们作为一种简单的“单例”值。node.js:如何在匿名函数中设置全局变量?

以下包含三种不同的方法来在NodeJS中声明全局范围内的变量(我认为)。函数change2()成功地将它们的值从“... one”更改为“... two”。然而函数change3()并没有将它们设置为“... three”。

如何从一个匿名函数中更改全局变量的值? - 我也尝试调用setter方法,但没有任何效果。 bind()调用只是一个无奈的猜测。

global.v1 = 'v1: one'; 
    var v2 = 'v2: one'; 
    v3 = 'v3: one'; 

    function change2() { 
     global.v1 = 'v1: two'; 
     v2 = 'v2: two'; 
     v3 = 'v3: two'; 
    }; 

    function change3() { 
     (function() { 
      global.v1 = 'v1: three'; 
      v2 = 'v2: three'; 
      v3 = 'v3: three'; 
     }).bind({v1:v1, v2:v2, v3:v3}); 
    }; 

    console.log (v1, v2, v3); 
    change2(); 
    console.log (v1, v2, v3); 
    change3(); 
    console.log (v1, v2, v3); 

输出为:

O:\node>node scope 
v1: one v2: one v3: one 
v1: two v2: two v3: two 
v1: two v2: two v3: two 

O:\node> 
+1

不是直接的答案,但文件“v1.js”的内容为'module.exports = {}'对于一个简单的单例更好。然后在你的其他模块中简单的require('./ v1')'。 –

+0

在'change3()'中你永远不会执行内部函数。 '.bind()'只是返回一个新的函数,但你永远不会真正调用它。 – jfriend00

+0

谢谢@ jfriend00发现。用'()'代替'.bind(...)'触发了调用,设置了“... 3”。 –

回答

1

change3()你从来没有真正执行的内部功能。 .bind()只是返回一个新的函数,但你永远不会真的调用这个新的函数。

如果你想调用它,你就必须在.bind()后添加的括号:

function change3() { 
    (function() { 
     global.v1 = 'v1: three'; 
     v2 = 'v2: three'; 
     v3 = 'v3: three'; 
    }).bind({v1:v1, v2:v2, v3:v3})(); // add parens at the end here 
}; 

但是,你甚至都不需要.bind()这里,因为它是你没有帮助。

function change3() { 
    (function() { 
     global.v1 = 'v1: three'; 
     v2 = 'v2: three'; 
     v3 = 'v3: three'; 
    })(); // add parens at the end here 
}; 
相关问题