user99999 user99999 - 2 months ago 16
Javascript Question

Difference between object and returning object from IIFE

Using

this
keyword inside functions of an object works, but refering to other functions without
this
doesn't. When I put out those functions before the object, both ways work. Why is that so?

var Obj = {
func1: function () {
console.log(this.func2()); // works
console.log(func2()); // doesn't work
},
func2: function () {
return 5;
}
};
Obj.func1();


But doing the same in IIFE:

var Obj = (function () {
function func1() {
console.log(this.func2()); // works
console.log(func2()); // works
}
function func2() {
return 5;
}
return {
func1: func1,
func2: func2
};
})();
Obj.func1();

Answer

This has nothing to do with the IIFE, in the first example you have an object literal, in the second regular functions.

Of course, object literals would need the name of the object (or this if the this-value is the object, like inside an object literal) followed by the property to access it, while named functions can be accessed anywhere in that scope by just using the name.

var obj = {
    prop : function() {...}
}

prop(); // fail ... undefined
obj.prop(); // works

// then _______________________________________________________________

function prop() {...}

prop(); // works fine 

This is really what you're doing, you've just wrapped it up in different objects and immediately invoked function expressions, so it looks somewhat the same, but it's not.

Comments