vars在Nodejs中存储在哪里?
在任何Web浏览器中执行以下脚本都会导致'wee'
被发送到控制台。 在节点中发送{}
。
var d = 'wee'; console.log(this.d);
我意识到,在这种情况下, this
指的是导出对象。 我知道global
variables,这不是我想要访问的。 另外,上面的脚本也没有在全局对象上设置d
。 它到底在哪里? 我可以通过console.log(d);
明确地访问它console.log(d);
在上面的脚本中,但似乎没有任何理由,在一些非标准的空间里隐藏起来。
我也意识到,删除var
会在global
对象上声明d
,这是预期的行为,尽pipe在顶级作用域将其值存储在与“裸”variables不同的位置上的var
看起来很愚蠢。 我的意思是,模块系统应该是防止全球污染的一种数字预防措施。 这里打破这个模式似乎很容易,做一些标准是很困难的。
d
也没有在module
对象上声明。
我没有理由为什么我要问这个问题,但我会回答第一个巨魔来与“但为什么你想做的durrrr”。
var d = {}; d.bleep = 'y'; var a = Object.keys(d); d.bloop = 'y'; d.blop = 'y'; var b = Object.keys(d); // c = b - a; var c = b.filter(function (item) { if(a.indexOf(item) === -1) { return true; } return false; }); console.log(a,b,c);
以同样的方式,我可以区分d
某些对象状态,我应该能够区分顶级范围的状态。 在浏览器中,这是window
对象,在顶层作用域中被引用。 我应该能够在脚本执行之前和之后评估环境的属性,以确定许多事情,其中之一是检查在任意脚本的顶部范围中声明的函数和variables,然后可以将其应用于导出对象。 这将使编程式生成模块包装程序变得容易,这些脚本不是作为模块编写的,而是将简单的forEach
应用于顶层函数和variables列表,以将whateverThisIs['varFunc']
分配给module.exports['varFunc']
。 ..
和东西…
这种行为看起来像一个匿名函数。 在一个匿名函数中, this
可以引用window
对象, var
s将不得不直接调用(因为它们在anon func的作用域中),泄漏的没有var
关键字的variables可能会在window
对象处结束。 我还没有阅读整个手册,也许这正是发生了什么事情,但我的印象是,每个模块在自己的上下文(窗口)中执行,并且节点之间通过使用global
和模块在模块上下文之间传递消息module.exports
…
我不知道。 我想知道。 如果你知道,让我知道。
因此,每个节点模块都被封装为一个函数的主体,如节点源代码所示
NativeModule.wrapper = [ '(function (exports, require, module, __filename, __dirname) { ', '\n});' ];
所以,如果你用var
声明一个variables,它对模块来说是函数本地的,基本上是该模块的一个私有variables。 它不是global
, module
, module.exports
或this
的属性。 如果你忘记var
,它将作为属性进入global
对象。 如果你明确地在this
上创build一个属性,那么this
属性会exports
到其他模块。
这是一个有希望启发的小程序。
var aDeclaredVar = '*aDeclaredVar*'; undeclaredVar = '*undeclaredVar*'; this.aThisProperty = '*aThisProperty*'; module.aModuleProperty = '*aModuleProperty*'; module.exports.anExportProperty = '*anExportProperty*'; console.log('this', this); console.log('this === exports', this === exports); console.log('this === module', this === module); console.log('this === module.exports', this === module.exports); console.log('aDeclaredVar', aDeclaredVar); console.log('undeclaredVar', undeclaredVar); console.log('this.aThisProperty', this.aThisProperty); console.log('module.aModuleProperty', module.aModuleProperty); console.log('module.exports.anExportProperty', module.exports.anExportProperty); console.log('global.undeclaredVar', global.undeclaredVar); console.log('global.aDeclaredVar', global.aDeclaredVar);
它的输出:
this { aThisProperty: '*aThisProperty*', anExportProperty: '*anExportProperty*' } this === exports true this === module false this === module.exports true aDeclaredVar *aDeclaredVar* undeclaredVar *undeclaredVar* this.aThisProperty *aThisProperty* module.aModuleProperty *aModuleProperty* module.exports.anExportProperty *anExportProperty* global.undeclaredVar *undeclaredVar* global.aDeclaredVar undefined