通过函数继承?

时间:2012-11-26 19:02:12

标签: javascript inheritance

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

典型:

ChildClass.prototype = new ParentClass();

替代方法:

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

SecondClass.prototype = clone(FirstClass.prototype);

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

1 个答案:

答案 0 :(得分:3)

因为您将调用您尝试继承的自定义类型(a.k.a.类)的构造函数。这可能有副作用。想象一下:

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

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

你的计数器已经增加了,但是你并没有真正创建一个有用的ParentClass实例。

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

注意:使用构造函数时,您可能拥有实例属性和共享属性。例如:

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