浏览器和节点之间有什么区别?例如:
节点上的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>
第二个日志不同,为什么?
解决方法
Node是JavaScript引擎,而不是浏览器.您在Node中看到未定义的特定原因,以及浏览器中的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.
在浏览器中,这是对窗口对象(浏览器的全局命名空间)的引用,用于所有未附加到对象的函数(例如,不像foo.bar()).在Node中,这不是对全局命名空间的引用.
注:节点解释器中的console.log(this.name)将打印Lulu,而不是未定义.那是因为,仅在REPL中,
> this === global true
进一步阅读@ How To Node: What is “this?”
好的,还有一个编辑按照@Šime Vidas’关于this
this
的评论提示:
- 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 07005.- When a function is called as a method of an object,its
this
is set to the object the method is called on.
更有趣的阅读由one of his blog posts one of his blog posts提供.