【问题标题】:node.js: how to set global variable from within anonymous function?node.js:如何从匿名函数中设置全局变量?
【发布时间】:2016-11-26 04:28:22
【问题描述】:

全局变量被认为是不好的做法,但我想将它们用作一种简单的“单例”值。

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

如何从匿名函数内部更改全局变量的值? - 我也试过调用一个没有效果的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>

【问题讨论】:

  • 不是一个直接的答案,但是一个包含module.exports = {} 内容的文件“v1.js”对于一个简单的单例来说效果更好。然后在您的其他模块中使用简单的require('./v1')
  • change3() 中,您从未真正执行过内部函数。 .bind() 只是返回一个新函数,但你从未真正调用它。
  • 感谢@jfriend00 发现。仅将 .bind(...) 替换为 () 会触发调用并设置“...三个”。

标签: node.js variables scope global anonymous


【解决方案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
};

【讨论】:

    猜你喜欢
    • 2014-08-20
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多