What is the purpose of o1.constructor = subType?

I read this blog https://www.cnblogs.com/nullc... while learning about js"s parasitic composition inheritance, and I don"t quite understand one of them. Paste it here and ask:

parasitic combinatorial inheritance: inherits properties by borrowing constructors and inherits methods through a mix of prototype chains. Idea: you don"t have to call the constructor of the parent class to specify the prototype of the subclass. all we need is a copy of the prototype of the parent class. In essence, you use parasitic inheritance to inherit the prototype of the parent class, and then assign the result to the prototype of the subclass:

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

question: what is the purpose of
o1.constructor = subType?
o1 is essentially an object instantiated by an empty constructor in Object.create, so o1 does not have any attributes, including the constructor attribute, which is understandable, but does not understand why the constructor of o1 points to subType? If it corrects the direction of constructor, why not write subType.prototype=o1 first and then o1.constructor = subType?


you can write subType.prototype=o1 first and then o1.constructor = subType;

these two statements do not conflict and can be interchanged.

What is the purpose of

o1.constructor = subType? This is to correct the constructor of subType. Because the subType.prototype=o1 code rewrites the subType prototype object, this prototype has lost contact with the original subType prototype object.

remember that when completely rewriting an object's prototype object, it's best to reassign the constructor. Otherwise, the constructor attribute of the subclass points to the superclass, not the subclass.

Menu