When we use prototype . we use like
function classA(){
}
function classB(){
}
classB.prototype = new classA();
why should we write it like that? why isn’t it?
classB.prototype = classA;
after I set the prototype is classA; then I log the classB.prototype. the console log like following
function classA(){
}
what’s that mean? I try to add some method into classA but I can NOT call them by using classB.prototype.BLABLA.
my english is not so good. so . I don’t know if I explain it well or not.
Because all instances of
classBwould inherit from the functionclassAwhich is usually not what you want. Instances ofclassBwould inherit all properties of function objects, such as.call[MDN] and.apply[MDN]. They would not inherit properties you assigning to an instance inside the constructor function or to the prototype ofclassA.You want each instance of
classBhaving the same properties as an instance ofclassA.But even
classB.prototype = new classA();is not a very good approach. What ifclassAexpects arguments passed to the constructor?Better let instances of
classBinherit fromclassA‘s prototype, like:And in the constructor, you are calling the parent constructor on the new instance:
Reference:
Object.create