开发者

JavaScript 'inheritance': constructor property is not correct

开发者 https://www.devze.com 2023-02-04 03:49 出处:网络
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 开发者_如何学Godic

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消