All else being equal, this
refers, when used directly within a function, to the object of which the function is a method (member), when that function is called in the typical way of obj.method()
. Directly means directly; use within a function nested within the method, whether anonymous or immediately-invoked or otherwise, does not qualify.
In your case
return (function() {
return this.num;
})();
the function is not a member of any object, hence there's no this
, hence this
is the global object (or null in strict mode).
Just because the function where you are using this
is nested within a function which is a method is not enough. The function where you are using this
must be the method itself.
To get the behavior you want, you have several alternatives:
getNum: function() {
return (() => this.num)();
}
This works because fat arrow functions use lexical this
.
Another idea, already shown in another answer:
getNum: function() {
var self = this;
return function() {
return self.num;
}();
}
In this context, by the way, there is no need to enclose the function in parentheses to force it to be a function expression that you can call immediately. Merely by virtue of being on the right side of the :
, it's already an expression.
Yet a third approach:
getNum: function() {
return function() {
return this.num;
}.call(this);
}
Here we are forcing the this
of the anonymous function to be the this
of getNum
, by explicitly using call
.
For the definitive answer, see How does the "this" keyword work?.
Note on the term "closure"
In your question, you appear to be using the term "closure" to mean "nested function". Although your nested, anonymous, immediately-invoked function may be a closure in some extremely narrow technical sense, using the term this way is likely to confuse both yourself and others. Your function does not satisfy either of the two following generally-accepted criteria for being a closure:
It does not "close over" (use) any variables from the surrounding scope.
It is not returned to the outside world as a function value carrying along with it references to such variables from the surrounding lexical scope.
Hence, it would be much clearer to simply refer to this function as a "nested function".