javascript“this”关键字在浏览器中按预期工作,但在node.js中没有

时间:2015-06-15 02:44:27

标签: javascript node.js

我知道我在这里犯了一个错误,但我无法弄清楚它是什么。

以下代码(非严格模式)在浏览器中可以正常工作,并向控制台输出“hello”。

function a() {
    console.log(this.bar);
}
var bar = "hello";
a();

但是当我在节点中运行它时,“undefined”是输出。

有谁知道原因?

2 个答案:

答案 0 :(得分:2)

在浏览器和节点中,函数内的this都指向全局对象(在本例中)。每个全局变量都是全局对象的属性。

代码在浏览器中有效,因为“默认范围”是全局范围。因此var bar声明一个全局变量,它变成全局对象的属性。

但是在Node中,每个文件都被视为模块。每个模块都有自己的范围。在这种情况下,var bar执行创建全局变量,但模块作用域变量。由于没有全局变量barthis.barundefined

答案 1 :(得分:0)

似乎在node中运行的代码被包装到一个函数中。类似下面的代码:

(function () {
  function a() {
    console.log(this.bar);
  }
  var bar = "hello";   
  a(); 
}());

您可以在browesr中尝试此代码,并且还会打印“undefined”。

您可以尝试节点中任何函数的console.log(arguments);return语句,看看发生了什么。

console.log(arguments);
return;
console.log("this will not be printed.");

将输出:

{ '0': {},
  '1':
   { [Function: require]
     resolve: [Function],
   ....
  '4': .... }

此外,您可以尝试以下代码:

var another = require("./another.js");

function a() {
    console.log(this.bar);
    console.log(this.baz);
}

bar = "hello";
a();

another.js

baz = "world"; // no var here

您将看到同时打印helloworld