Long story short:
1. The IIFE is executing in the context of the window
I was wrong,
see RobG's comment.
2. this
thus refers to the window
inside the IIFE, since it is not set by default.
3. Your doing this.defaultNumber = 5;
is hence equivalent to
window.defaultNumber = 5;
4. The second method executes in the context of numberManipulator
and so logging this.defaultNumber
is equivalent to numberManipulator.defaultNumber
which was never set by you. Hence, it is undefined.
Explanation on this
:
Inside any function, the this
keyword refers to the current context in which the function is executing. It doesn't matter where you defined that function inside your codebase. All it matters in what context are you calling it. In your current case, you're calling the IIFE in the context of the window. Doing:
const numberManipulator = (function() {
// MAGIC
})();
amounts to:
- running an IIFE in the
window
context.
- assigning the result it returned to a constant.
However, the context of a function may be changed by using .call
, .apply
, or by simply calling that method as a property of another object. In your second log, this.defaultNumber
, this
refers to the object since you called the method using numberManipulator.doubleNumber(20);
. Calling methods using object.prop()
sets their context (=this
) to that object
.
Hope that helps! :D