gpt4 book ai didi

javascript - 浏览器和 Node 有什么区别?

转载 作者:数据小太阳 更新时间:2023-10-29 05:08:39 25 4
gpt4 key购买 nike

浏览器和 Node 有什么区别?例如:

setName.js 在 Node 上:

var setName;
setName = function (name) {
return this.name = name;
};
setName("LuLu");
//LuLu
console.log(name);
//undefined
console.log(this.name);

setName.html 在浏览器中:

<script>
var setName;
setName = function (name) {
return this.name = name;
};
setName("LuLu");
//LuLu
console.log(name);
//LuLu
console.log(this.name);
</script>

第二个日志不一样,为什么?

最佳答案

Node 是一个 JavaScript 引擎,而不是浏览器。您在 Node 中看到 undefined,而在浏览器中看到 Lulu 的具体原因是什么? Differences in the global namespace :

In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

在浏览器中,this 是对 window 对象(浏览器的全局命名空间)的引用,用于调用所有未附加到对象的函数(例如 不像 foo.bar() 那样。在 Node 中,this 根本不是对全局命名空间的引用。


N.B. Node 解释器中的 console.log(this.name) 将打印 Lulu,而不是 undefined .那是因为,仅在 REPL 中,

> this === global
true

进一步阅读@ How To Node: What is "this?"


好的,根据 @Šime Vidas' 的提示再编辑一次关于 this 的评论在 ES5 strict mode :

  • In the global context (outside of any function), this refers to the global object, whether in strict mode or not.
  • When the this keyword occurs inside a function, its value depends on how the function is called.
  • When a function is called as a method of an object, its this is set to the object the method is called on.

更多有趣的阅读礼貌 Juriy Zaytsev (aka @kangax)one of his blog posts .

关于javascript - 浏览器和 Node 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8624913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com