0

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)

Community
  • 1
  • 1
JS-JMS-WEB
  • 2,555
  • 3
  • 17
  • 26
  • 2
    You probably meant to manipulate each "type"s `prototype` outside the function. It will probably solve your problems – Amit Jun 28 '15 at 13:23
  • @Amit I know it fixes it but why this particular behaviour? – JS-JMS-WEB Jun 28 '15 at 13:24
  • This is just automatic semicolon insertion messing with you. Watch those semicolons. – Benjamin Gruenbaum Jun 28 '15 at 13:32
  • Are you aware that the `parent.prototype` property refers to the prototype used when instantiating a new object with `new parent()`, and NOT the actual prototype of the instance itself? In order to access the actual prototype you'd need to use Object.getPrototypeOf(), or the (non-standard) `__proto__` property. – Matt Browne Jun 28 '15 at 13:34
  • @JS-JMS-WEB because the function itself is defining the Constructor. The prototype is defined based off of the Constructor. – Danny Blue Jun 28 '15 at 13:36

1 Answers1

4

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
}());
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • But I get the similar result when I do `var parent=function(){ parent.prototype.method1= function() {} parent.prototype.property = true; }, child=function() { child.prototype = new parent(); };new child(); // normal new child(); //parent's prototype` – Amit Joki Jun 28 '15 at 13:37
  • "if I remove this, I get an undefined error in IFFY ?" my answer solves _that part_. – Benjamin Gruenbaum Jun 28 '15 at 13:41