user1354934 user1354934 -4 years ago 62
Javascript Question

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 is
console.log(this.defaultNumber
showing
undefined
but if I
console.log(defaultNumber
, it shows
5
? I thought that it would show undefined for the latter.

Thanks

Answer Source

You should read How does the “this” keyword work?

When the IIFE is called, its this is 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 (window in a browser) object called defaultNumber and assigns it a value of 5.

If the return statement should really be:

return {doubleNumber: doubleNumber}

then the IIFE returns an object reference to numberManipulator. When called as:

numberManipulator.doubleNumber(20)

then this within doubleNumber is numberManipulator, which doesn't have a defaultNumber property so this.defaultNumber returns undefined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download