Why is this.defaultNumber undefined? Trying to understand IIFE
Given this code:
const numberManipulator = (function() {
this.defaultNumber = 5;
const doubleNumber = function(num) {
console.log(this.defaultNumber);
return num !== undefined ? num * 2 : new Error('no number provided!');
}
return {
doubleNumber
}
})();
const test = numberManipulator.doubleNumber(20);
Why console.log(this.defaultNumber
does it show undefined
, but if I do console.log(defaultNumber
, does it show 5
? I thought it would show undefined for the latter.
thank
source to share
You should read How does the "this" keyword work?
When the IIFE is called its not set, so it defaults to the global object, so in:
const numberManipulator = (function() {
this.defaultNumber = 5;
...
})();
this.defaultNumber = 5
creates a property of the global (browser window) object named defaultNumber and sets it to 5.
If the return statement should be valid:
return {doubleNumber: doubleNumber}
then the IIFE returns a reference to the numberManipulator object. When called like:
numberManipulator.doubleNumber(20)
then in doubleNumber it is numberManipulator, which does not have a defaultNumber property, so it this.defaultNumber
returns undefined.
source to share
Shortly speaking:
1. IIFE performs in context window
, I was wrong, see RobG's comment.
2. this
is thus referenced window
inside the IIFE as it is not set by default.
3. Your occupation this.defaultNumber = 5;
is therefore equivalent to
window.defaultNumber = 5;
4. The second method is executed in context numberManipulator
, so the entry is this.defaultNumber
equivalent to numberManipulator.defaultNumber
one that you never set. Hence it is undefined.
Explanation on this
:
Within any function, a keyword this
refers to the current context in which that function is executing. It doesn't matter where you defined this function within your codebase. It all matters in what context you call it. In your current case, you are calling IIFE in the context of a window. Performance:
const numberManipulator = (function() {
// MAGIC
})();
is:
- launching IIFE in context
window
. - assigning the result returns a constant.
However, the context of a function can be changed using .call
, .apply
or simply by calling this 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()
set their context ( =this
) to object
.
Hope it helps!: D
source to share