I have read a couple of articles on the web explaining this in Javascript. While the articles
have helped a lot, the behavior shown below is still unclear to me.
Here it says:
In the global execution context (outside of any
function), this refers to the global object, whether in strict mode or not.
If so, can someone please explain the behavior (noted in the comments) when the following code is run with node.
console.log(this); // Returns an empty object: {}.
// Why does this line not return the global object.
var somefunc = function(name) {
console.log(this);
}
somefunc(); // Returns the the global object. I think I understand this. The function is
// invoked in a global context.
somefunc.call(this); // Again returns the empty object. Why?
Thanks for your help.
EDIT (as requested by below by the moderators) *How is this question and the chosen answer different from the one linked above*
I think both the question and certainly the answer here is clearer than the one that is considered a duplicate. The answer here clarifies what node is doing by giving example code, which is more helpful.
The first and the third showing of this should be identical in any case: in first case you just output the current value of this, and in the third you pass, again, the current value of this into somefunc (as a context argument).
But in the second, it's different: you call this function without assigning it any specific context, so this inside it points to a global object.
Why do you get an empty object as a result? One explanation is that your code is actually wrapped into some generic closure, like this:
var sandbox = {};
(function() {
console.log(this); // 1
var somefunc = function(name) {
console.log(this);
}
somefunc(); // 2
somefunc.call(this); // 3
}).call(sandbox);
As this function is called in sandbox context, both 1 and 3 point to sandbox - that is an empty object. 2 is different: you don't supply any context to this function call, that's why inside the function (when it's called that way) this points to global.
And that's exactly what happens when you try to access this in a global context of Node module. I'll quote an explanation from this discussion:
Node's modules are wrapped in a closure, which is evaluated in the this-context of the
exportsobject. So, if you dovar a = 3, then it won't be added tothis,global, orexports. But, if you dothis.a = 3then it'll be added tothisandexports.
Note that it's quite different from using the code as it is within a browser. It's not wrapped in any closure, so all the calls - 1, 2 and 3 - are referring to the global object. And that's, as you know, window.