在Javascript中为派生类定义构造函数

时间:2014-09-28 02:07:01

标签: javascript oop

传统观点认为,要在Javascript中模拟OOP,我们会在功能和原型方面做所有事情:

var fooObject = function () {
  //Variables should be defined in the constructor function itself,
  //rather than the prototype so that each object will have its own variables

  this.someProperty = 5; //Default value
};

//Functions should be defined on the prototype chain so that each object does not
//have its own, separate function methods attached to it for performing the same
//tasks.

fooObject.prototype.doFoo = function () {
  //Foo
}

现在,要创建派生类,我们执行:

var derivedFromFoo = new foo();

但是如果我们想在构造函数中为派生对象做一些其他的事情会发生什么?喜欢设置其他属性?我们可以做点什么吗

var derivedFromFoo = function () {
  this = new foo();
};

1 个答案:

答案 0 :(得分:3)

new foo();

这是一个实例,而不是一个类。

要创建派生类,您需要创建一个新函数,从其内部调用基本ctor,然后将新函数的prototype设置为从基础prototype创建的对象:< / p>

function Derived() {
    Base.call(this);
}
Derived.prototype = Object.create(Base.prototype);

有关详细信息以及更长,更正确的实现,请参阅我的blog post

相关问题