首页 > 解决方案 > 为什么“this”关键字总是在 node.js 中返回 undefined?

问题描述

每个人我都是 JS 的初学者。我读过文章。据我所知,“this”关键字是一个全局对象。如果我们使用“strict”,那么它将是未定义的。.为什么我在javascript浏览器和Node.js版本中得到不同的输出。有人可以解释一下吗?

scenario1:

(Javascript Browser):

var count=5;

console.log(count);  //5

console.log(this.count); //5


(Node.JS 12.13.0)

var count=5;

console.log(count);  //5

console.log(this.count); //undefined


scenario2:

(Javascript Browser):

function ghost() {
  console.log(this.boo);
}

ghost(); // ABC

var boo = 'ABC';

ghost(); //ABC

(Node.JS 12.13.0)

function ghost() {
  console.log(this.boo);
}

ghost(); // undefined

var boo = 'ABC';

ghost(); //undefined

标签: javascriptnode.jsthis

解决方案


推荐阅读