I was confused with this following code in javascript.
var x=(function(){
var customObject = function(){};
customObject.prototype.sayHello=function(){
alert("hello");
};
return customObject;
})();
//var y=new x();// If I uncomment this line and comment the next line "var
//y=x;" the code works
var y=x;
y.sayHello();
This code doesn't say hello but it does when I remove the comment. I read that IIFE executed immediately after it is defined. So, it should assign the customObject to x directly.
My question is that why I need to create a new instance of x to say hello. It is not clear to me how IIFE is working here.
Please help me to understand this concept. Thank you in advance :-) .
You're correct that the customObject
is assigned to x
. But customObject
(and therefore x
) does not have a sayHello
property. It has a prototype
property, and that has a sayHello
property.
When you do y=x
and then y.sayHello()
, you're trying to call customObject.sayHello
, which doesn't exist.
When you do y=new x()
, you create an object whose prototype is the customObject.prototype
object. Then, when you call y.sayHello()
, the sayHello
function is found via the prototype chain.
This isn't really related to your use of an IIFE. You'd get the same result if you just wrote:
var x = function() {}
x.prototype.sayHello = function() {
alert("hello");
}
instead of the IIFE.