2012-01-15 63 views
0

我们知道,在一个铬窗,当执行下面的代码节点JS简单的功能和`this`

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文件?想更多地了解它,所以如果可能的话,请提供指向这篇文章和教程的链接。

+0

放强调'is_function_test' – clyfe 2012-01-15 08:51:05

回答

1

Node中的全局对象的行为不同。一个模块有其自己的范围。你只能创建一个真正的全球使用“global.foo = true”

0

好问题!

sample.js

function is function test(){ 
    console.log("this is " + this); 
} 
test(); 

铬使用以下代码显示在时间,测试()在DOMWindow的范围正在运行:

this is [object DOMWindow] 

节点示出了在该时间,测试()运行在全局对象的范围内:

this is [object global] 

但自从test()已被定义为模块sample.js的一部分,this.testtest()正在运行时未定义。

+0

http://nodejs.org/api/globals.html#globals_global的原因是不是你所提到的情况 – Tamil 2012-07-10 10:21:28

+0

当测试()正在运行,'this'引用全局名称空间对象。当test()在模块内部定义时,它不是全局命名空间的一部分,因此global.test是未定义的。 没有一个有用的解释的投票是非常浪费每个人的时间。 – mike 2012-07-10 18:33:50

+0

你的评论比你的回答更清晰。你自己回答了downvote的原因:)这很好,'test()已经被定义为模块sample.js'的一部分,但是'test.test'在test()运行的时候是未定义的。 – Tamil 2012-07-10 18:45:46

0

基本上是以@igl提到的模块有自己的own scope

你可以假设节点包住一个

(function() { 
// Your module code goes here 
})() 

所有module代码执行前。因此为模块本身创建一个本地范围。

原因: 它会阻止全球范围内从越来越污染

场景:说你有module样品这在它有一个测试功能,并且还另一个模块说SAMPLE2这还有一个测试函数。如果节点没有为您的示例和sample2创建本地范围,则测试函数中的任何一个都会覆盖另一个。

你也需要了解节点只在一个模块的module.exports对象感兴趣

例子:

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(); 

这里没有var盈的测试因此它在浏览器窗口范围内变成global。现在尝试在本地节点实例执行上述

hai: 'but i will be there', 
test: [Function] } 
function is function() { 
    console.log("function is ", this.test); 
} 

你应该看到的global对象属性的大名单,并测试函数的定义。 样品不会出现在列表中,但