Considering the fallowing example :
function A(obj) {
}
B.prototype = new A;
B.prototype.constructor = B;
function B(obj) {
A.call(this, obj);
}
where B should inherit the prototype from A. Is this code correct? Why is it that the function A is called once when the script is parsed, without any instance from A or B being declared? Is it because of the fallowing line?
B.prototype = new A;
If so, how can B inherit A without calling function A in the definition.
You can avoid calling A again if you use Object.create
Object.create creates a new object that has the given parameter as its prototype (the actual prototype, not the “prototype” property). It is not present in old browsers (IE < 8, FF < 4) but you can (for our purposes) create your own version if you want to. The basic idea is precisely creating a version of
Athat does nothing (and therefore can be called wihthout undesired side effects)Another thing you can do is never put logic inside the constructor function and instead put it in a separate
initmethod that must be called afterwards.