function A() {
this.myProp = document.createElement(“div”); }
function B(id) {
this.myProp.id = id;
document.body.appendChild(this.myProp); }
B.prototype = new A();
window.onload = function() {
new B("hello");
new B("goodbye"); }
What happens here is that I end up with one div with id “goodbye”. What I would like is two divs with the specified ids.
I have been able to fix this problem by creating a method of “A” which creates the element.
How could I fix it without using the method?
You have to call the constructor
A()when creating anew B():If you want
Binstances to inherit fromA.prototype, don’t setB.prototypeto anAinstance, but useObject.create()– or a custom implementation for legacy browsers – to avoid a constructor invocation: