JS-JMS-WEB
JS-JMS-WEB

Reputation: 2625

JavaScript line with semicolon behaving strange

I am facing a strange issue with this code. I can fix it easily but I would like to know why this is happening.

If I comment out child below I get undefined error in IFFY. The function is located in global scope and should work everywhere. Not sure why?

JSFiddle link

parent=function(){   
    parent.prototype.method1= function() {}
    parent.prototype.property = true;
}

child=function() {
    parent.call(this);    
    child.prototype = new parent(); 
}

child; // This is important, if I remove this, I get an undefined error in IFFY ?


(function(){
    var instance1 = new child();
    console.log( instance1 );  // Empty Object

    var instance2 = new child();
    console.log( instance2 ); // Object is not empty

}());

(there are also other issues with this code which I asked about in an extra question)

Upvotes: 0

Views: 75

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

This is just automatic semicolon insertion messing with you. When you omit the child you get:

child=function() {
    parent.call(this);    
    child.prototype = new parent(); 
}

(function(){
    var instance1 = new child();
    console.log( instance1 );  // Empty Object

    var instance2 = new child();
    console.log( instance2 ); // Object is not empty

}());

Which is parsed as:

child=function() {
    parent.call(this);    
    child.prototype = new parent(); 
}(function(){ // FUNCTION CALL
    var instance1 = new child();
    console.log( instance1 );  // Empty Object

    var instance2 = new child();
    console.log( instance2 ); // Object is not empty
}());

Upvotes: 4

Related Questions