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?
Node is a JavaScript engine, not a browser. The specific reason that you see
undefinedin Node, andLuluin a browser? Differences in the global namespace:In the browser,
thisis a reference to thewindowobject — the browser’s global namespace — for all functions which are invoked unattached to an object (e.g. not likefoo.bar()). In Node,thisis simply not a reference to the global namespace.N.B.
console.log(this.name)in a Node interpreter will printLulu, notundefined. That’s because, in the REPL only,Further reading @ How To Node: What is “this?”
Okay, one more edit as prompted by @Šime Vidas’ comment regarding
thisin ES5 strict mode:More interesting reading courtesy of Juriy Zaytsev (aka @kangax) in one of his blog posts.