JavaScript js 在 node 和 window 中的全局对象

ane · February 11, 2014 · Last by saiga replied at February 11, 2014 · 3342 hits

最近看到一段 js,网上也没找到所以然 (node 中执行)

var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
      };
    }
  };
  console.log(object.getNameFunc()());

(浏览器中执行)

var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
      };
    }
  };
  alert(object.getNameFunc()());

这两种结果是不一样的,我相信,一定和浏览器的 windows 对象有关系,只是我不太了解 node,还请牛人解释一下

在浏览器 global context 中 var name = "The Window";this.name = "The Window" 等价。

if (!("a" in window)) {
    var a = 1;
}
alert(a);

你看看这题,alert 弹出的是啥?

而 nodejs 虽然有一个跟 window 类似的 global,但是每个文件(模块)都有自己的执行上下文,所以 var name = "The Window" 在 nodejs 中是以局部变量存在。

#1 楼 @saiga 意思是,在浏览器中,无论在什么地方,this 指的都是 Object window?,这样的话,似乎就可以说通了

#1 楼 @saiga 和我想的一样,未定义,

#3 楼 @u1378130755 JS 在 window 下用 var 声明的变量会赋到 window 对象上,所以 那题 var a = 1 的声明被提前,"a" in window 永远为 true。

并不是 this 永远指向 true。但是你必须清楚 JS 的 this 很没节操,谁来调的函数就是谁。

fn1 = object.getNameFunc(); // getNameFunc 由 object 调用,所以 this 指向 object;
fn1();  // 等价 fn.call(this); 此时 this 指向 window

You need to Sign in before reply, if you don't have an account, please Sign up first.