JavaScript 'inheritance': constructor property is not correct
Please help explain the following result (tested on Firefox 3.6). How come this.constructor points to A inside prototype, if "this" is clearly of type B? I was under illusion that 开发者_如何学Godictionary is traversed from topmost level down prototype chain, but it doesn't seem to be the case here:
A=function() {}
A.prototype.copy=function() {
return new this.constructor();
}
B=function() {}
B.prototype=new A();
var b=new B();
var bcopy=b.copy();
var cond1=bcopy.constructor==B // false
var cond2=bcopy.constructor==A // true
var b = new B;
b.constructor == A; // true
Thus, your copy()
function is creating a new A. If, however, you add this line:
B.prototype.constructor = B;
...you will get the results you were hoping for.
精彩评论