什么是浏览器和节点之间的区别? [英] what's the difference between Browsers and Node?
问题描述
什么是浏览器和节点之间的区别?例如:
what's the difference between Browsers and Node? for instance:
setName.js
的节点:
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>
在第二个日志是不同的,为什么呢?
the the second log is different,why?
推荐答案
节点是一个JavaScript引擎,而不是浏览器。你看到的未定义
在节点的具体原因,而露露
在浏览器? rel=\"nofollow\">差异:
Node is a JavaScript engine, not a browser. The specific reason that you see undefined
in Node, and Lulu
in a browser? Differences in the global namespace:
在浏览器中,顶层作用域是全局范围。这意味着,在浏览器中,如果你在全局范围内 VAR东西
是定义一个全局变量。在这个节点是不同的。顶层范围并不全局范围; VAR东西
内部节点模块将是局部的模块。
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.
在浏览器中,这个
是 A参考窗口
对象 - 浏览器的全局命名空间 - 的所有功能对其调用独立的一个对象(如的不的如 foo.bar()
)。在节点,这个
根本就没有到全局命名空间的引用。
In the browser, this
is a reference to the window
object — the browser's global namespace — for all functions which are invoked unattached to an object (e.g. not like foo.bar()
). In Node, this
is simply not a reference to the global namespace.
NB 的console.log(this.name)
在节点间preTER会打印露露
,而不是未定义
。这是因为,在REPL只,
N.B. console.log(this.name)
in a Node interpreter will print Lulu
, not undefined
. That's because, in the REPL only,
> this === global
true
延伸阅读@ 如何节点:什么是?这个
好吧,按照提示通过 @ SIME维达斯评论有关的 这个
中的 ES5严格模式:
Okay, one more edit as prompted by @Šime Vidas' comment regarding this
in 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(又名@kangax)中的他的博客文章之一。
这篇关于什么是浏览器和节点之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!