我们知道,在Chrome窗口中,当执行以下代码时
function test(){
console.log("function is " + this.test);
}
test();将test作为函数添加到window对象中,并显示
function is function test(){
console.log("function is " + this.test);
}在控制台中。
当我将相同的代码放入文件sample.js中并使用node执行时
nodejs$ node sample.js它在给予
function is undefined但是当我直接在node终端中执行相同的代码时
nodejs$ node
> function test(){
... console.log("function is " + this.test);
... }test();它显示与浏览器相同的输出。
谁能解释一下为什么会发生这种情况,以及V8引擎是如何执行Javascript文件的?我想知道更多关于它,所以如果可能的话,请提供链接到文章和教程这一点。
发布于 2012-01-15 16:53:25
Node中的全局对象的行为有所不同。模块有自己的作用域。只能使用"global.foo = true“创建一个真正的全局
发布于 2012-01-16 00:51:00
问得好!
在sample.js中使用以下代码
function is function test(){
console.log("this is " + this);
}
test();Chrome显示,当时,test()正在DOMWindow作用域中运行:
this is [object DOMWindow]节点显示当时test()正在全局对象的作用域中运行:
this is [object global]但由于test()已被定义为模块sample.js的一部分,因此在运行test()时this.test是未定义的。
发布于 2012-07-10 18:19:28
您可以假设节点将所有module代码包装在一个
(function () {
// Your module code goes here
})() 在执行它之前。因此为模块本身创建了一个本地作用域。
场景:假设你有一个包含测试函数的module示例,还有另一个模块sample2,它也包含一个测试函数。如果node没有为您的示例和sample2创建本地作用域,那么这两个测试函数中的任何一个都会覆盖另一个。
示例:
var sample = 'you will not see me in global object';
hai = 'but i will be there';
test = function () {
console.log("function is ", this.test);
}
console.log(global);
test();这里,在hai和test前面没有var,因此它变成了与浏览器窗口范围中相同的global。现在,尝试在本地节点实例中执行上述操作
hai: 'but i will be there',
test: [Function] }
function is function () {
console.log("function is ", this.test);
}您应该会看到一个很大的global对象属性列表,以及测试函数的定义。样本不会在列表中,但是
https://stackoverflow.com/questions/8868512
复制相似问题