0

While learning about Parasitic Combination Inheritance,I saw an example in a blog and feel doubt.It is :

<script>
function inheritPrototype(subType,superType){
      var o1=Object.create(superType.prototype) ;      
      o1.constructor = subType;                    
      subType.prototype=o1;               
}
</script>

I know it wants to make subType inherit superType,but I dont know what is the purpose of "o1.constructor = subType;".My guess are below:

1.What Object.create do is :

Object.create =  function(o){
        var F = function (){};
        F.prototype = o;
        return new F();
    };

As o1 is created by F which is from Object.create,it doesn't have any property including constructor.So here we need to give o1 a constructor property.But if so,why we must make o1.constructor point to subType?

2.To fix constructor.But if so,why we don't first write subType.prototype=o1 and then write o1.constructor = subType?We fix the constructor because the prototype has been rewriteen,right?

3.Some other reasons?

PS:The question is quite different from "Parasitic Combination Inheritance" in Professional JavaScript for Web Developers .Although the codes are quite the same,the question is actually different.

Chor
  • 833
  • 1
  • 5
  • 14
  • Yes,our codes are very the same but the question is actually different.I know why to reset the constructor but don’t know why we first reset the constructor and then to rewrite the prototype.As we know,it is because we rewrite the prototype that we need to reset the constructor later.So here,maybe the order is wrong? – Chor Feb 25 '19 at 04:57
  • I mean:first write "subType.prototype=o1; ",and then write "o1.constructor = subType;" – Chor Feb 25 '19 at 04:58
  • Alright. I’ve withdrawn the flag. – Aankhen Feb 25 '19 at 05:02
  • 1
    The order of those two statements doesn't matter, they don't affect each other; so if you swap those statements the resulting effects are identical. – Paul Feb 25 '19 at 15:17

0 Answers0