【问题标题】:Inheritance via a function?通过函数继承?
【发布时间】:2012-11-26 19:02:12
【问题描述】:

我正在学习 Javascript 中的 OOP 基础知识,并遇到了一个与我通常看到的不同的继承示例。

典型:

ChildClass.prototype = new ParentClass();

替代方法:

function clone(object) {
  function OneShotConstructor(){}
  OneShotConstructor.prototype = object;
  return new OneShotConstructor();
}

SecondClass.prototype = clone(FirstClass.prototype);

为什么在创建原型是另一个对象的对象时首选后者?

【问题讨论】:

标签: javascript inheritance


【解决方案1】:

因为您将调用您尝试继承的自定义类型(又名类)的构造函数。这可能会产生副作用。想象一下:

var instancesOfParentClass = 0;
function ParentClass (options) {
  instancesOfParentClass++;
  this.options = options;
}

function ChildClass () {}
ChildClass.prototype = new ParentClass();

您的计数器已增加,但您并没有真正创建有用的 ParentClass 实例。

另一个问题是,所有实例属性(请参阅this.options)都将出现在 ChildClass 的原型上,而您可能不希望这样。

注意:使用构造函数时,您可能有instance 属性和shared 属性。例如:

function Email (subject, body) {
  // instance properties
  this.subject = subject;
  this.body = body;
}

Email.prototype.send = function () {
  // do some AJAX to send email
};

// create instances of Email
emailBob = new Email("Sup? Bob", "Bob, you are awesome!");
emailJohn = new Email("Where's my money?", "John, you owe me one billion dollars!");

// each of the objects (instances of Email) has its own subject 
emailBob.subject // "Sup? Bob"
emailJohn.subject // "Where's my money?"

// but the method `send` is shared across instances
emailBob.send === emailJohn.send // true

【讨论】:

  • 没错,你不应该仅仅为了设置继承而运行构造函数。但是,还有其他问题,例如构造函数属性不正确。我有一篇博客文章解释了 JS js-bits.blogspot.com/2010/08/… 中良好继承的原因
  • gryxxly,我是编程新手,请原谅我可能听起来很愚蠢。您能否扩展“所有实例属性都将出现在 ChildClass 上”的意思?这个例子实际上来自 Eloquent JS,在书中他们为第二个类创建了一个与第一个不同的方法,但仍然需要在第一个类的上下文中使用第一个方法。这和你解释的有关吗?
  • 所以不,它与您在谈论的内容并没有真正的关系,那件事(如果我理解正确的话)被称为“调用父自定义类型的方法”,有时代码需要-reuse(假设您在继承的对象中只有一点点自定义功能,其余的都与父自定义类型完全相同)。想想特定的Email 类型,在发送之前需要将"Sent from my iPhone" 添加到this.body 的末尾。
  • 感谢您对此进行扩展。我确实看到在这种情况下调用构造函数会导致问题。
猜你喜欢
  • 2015-02-23
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多