【问题标题】:Constructor assignment on prototypal inheritance原型继承的构造函数赋值
【发布时间】:2012-02-28 20:06:58
【问题描述】:

在进行原型继承时,会要求将孩子的构造函数引用回下面的自身,

A = function() {} 
B = function() {} 
B.prototype = new A;
B.prototype.constructor = B;

如果不这样做会产生什么不利影响?

编辑

  • 正如@GGG & @CMS 所解释的,构造函数对齐不需要 对new Child(...) 创建子对象的影响,但是 有必要稍后正确反映子对象的构造函数。
  • @GGG 还提出了一种防御性替代方案来扩展 原型链。而Child.prototype = new Parent(...) 包括父级对子级的属性,Child.prototype = Object.create(Parent.prototype) 不包括。

【问题讨论】:

标签: javascript prototypal-inheritance


【解决方案1】:

首先,请不要这样做:

B.prototype = new A;

改为这样做(shimObject.create 用于旧浏览器):

B.prototype = Object.create(A.prototype);

至于constructor,如果你不这样做,什么都不会破坏,但如果你不这样做:

A = function() {};
var a = new A();
console.log(a.constructor); // A

B = function() {};
var b = new B();
console.log(b.constructor); // A (!)

...将原型的constructor 属性设置回实际的构造函数允许您这样做:

B.prototype.constructor = B;
var b = new B();
console.log(b.constructor); // B

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多