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

Defining a constructor for a derived class in Javascript

本文关键字:定义 构造函数 派生 Javascript      更新时间:2023-09-26

传统的观点是,要在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();
};
new foo();

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

要创建派生类,需要创建一个新函数,从函数内部调用基ctor,然后将新函数的prototype设置为从基prototype:创建的对象

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

有关更多详细信息和更长、更正确的实现,请参阅我的博客文章。