I’ve tried following code in ie, firefox and node.js
var x = 10;
var o = { x: 15 };
function f(){
console.log(this.x);
}
f();
f.call(o);
the results in browsers are 10, 15, but the result in node.js is undefined, 15.
Please explain to me what is the different behavior of “this” keyword in browsers and node.js? I’ve read many pages but there wasn’t any obvious answer.
Thanks in advance.
Javascript files loaded in Nodejs are automatically wrapped in anonymous functions.
So in Node what you are really running is:
The browser does not do this. The issue is that now in Node
xis just a normal variable in the scope of the function, it is not part of the global scope. When you callf()this way,thiswithinfis the global scope.If directly put
xon the global scope, it will work in both cases.That will place
xon thewindowglobal object in the browser, and theglobalglobal object in Node.Generally, you do not load things globally in Node, instead you group your code into modules, as described here. There is info about the various global things you can access here. And if you are curious about the wrapper, you can see it here.