Node.js环境下JavaScript中this的问题?

function myFunc(){
    this.name="func";
    console.log(this);
}
function myFunc2(){
    console.log(this.name);
}
myFunc();
myFunc2();
new myFunc();
new myFunc2();
console.log(this)

在node.js执行上述代码,第一次执行两个函数this指向的是全局,第二次用了new构造器后指向的是实例化的对象本身,但是最后一个外部的console.log()中为什么this输出的却是空的对象({})呢?

阅读 9.7k
2 个回答

看帖子还没关,我来总结下,如果问题已经解决,希望早点关帖

1. 直接调用的 this

参考 this - 函数上下文

myFunc();
myFunc2();

这两个调用属于直接调用,在非严格模式下,直接调用函数,函数中的 this 指向全局对象。在 NodeJS 环境下,全局对象是 global,所以

function myTest() {
    console.log(this === global);
}
myTest();         // true

2. 构造函数中的 this

参考 this - 构造函数中的 this

new myFunc() 这种调用是把 myFunc 当作构造函数使用。这时候,函数中的 this 指向新创建的对象。如果构建函数没有通过 return 语句返回特定的值,构建函数通过 new 调用返回上述新创建的对象。

function MyClass(name) {
    this.name = name;
}

var obj = new MyClass("hello");
console.log(obj.name);
// hello

3. console.log(this) 为什么不是 global

NodeJS 的每一个文件是被当作一个模块来封装的,所以,你直接写在文件中的代码,实际可能是被封装成这样的

function factory() {
    function myFunc() {}
    function myFunc2() {}
    console.log(this);
};

// 定义模块
var module = {
    factory: factory;
};

// 构建模块
module.factory();

也就是说,console.log(this) 中的 this 是指向外部的 module 而不是 global

好,现在你要问,那为啥打印出来没有 factory ——因为这个 module 是我假设的,实际 NodeJS 如何调用需要去看它的实现相关的资料或者源码,也许它是这样调的呢

var module = {};
factory.call(module);

顶级作用域this指向全局对象

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题