I have this type of code for prototypal inheritance in Javascript.
function A() {
this.a = 1;
}
function B() {
someEl.innerHTML(this.a);
}
B.prototype = new A();
However, I am wondering if there is a better way to do it, preferably one that brings the prototype declaration into the declaration of B.
I tried setting this.prototype in B, but it just showed this.a as undefined.
So, is there a better way to do this?
The
prototypeproperty should be used only in constructor functions,this.prototypedoesn’t makes sense becausethisjust the new object instance, not the constructor.Assign the
prototypeinside the constructor itself isn’t a good idea, since that assignment will be executed each time you create a new object (bynew B();).Your code seems perfectly valid to me, the only thing that you should be aware of, is that if you replace the
prototypeproperty of a constructor, like you do it withB.prototype = new A();theconstructorproperty of the object instances ofB, will point toA.Usually is recommended to restore that property, e.g.:
Give a look to: