what's the difference between Browsers and Node?

时间秒杀一切 提交于 2019-12-19 03:10:52

问题


what's the difference between Browsers and Node? for instance:

setName.js on Node:

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

setName.html in browser:

<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?


回答1:


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:

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.

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.


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

Further reading @ How To Node: What is "this?"


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.

More interesting reading courtesy of Juriy Zaytsev (aka @kangax) in one of his blog posts.




回答2:


Your browser code has the window host object. Node does not have that host object. When you set this.name, you are actually setting it to the window object aka making a global variable.

window.name === this.name // true



来源:https://stackoverflow.com/questions/8624913/whats-the-difference-between-browsers-and-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!