0

私は JavaScript が初めてで、パラメーターを受け取るコンストラクターがある場合に継承について頭を悩ませようとしています。

と呼ばれるベースオブジェクトがあるとしますBase:

function Base(param1, param2) {
   // Constructor for Base that does something with params
}

たとえばBaseChild、 Base から継承するという別のオブジェクトと、から継承するChildという別のオブジェクトが必要ですBaseChild

基本的な JavaScriptBaseChildのコンストラクターを作成してChild使用するにはどうすればよいでしょうか(つまり、特別なプラグインを使用しません)。


ノート:

次のように BaseChild を作成できると思いました。

var BaseChild = new Base(param1, param2);

param1しかし、私はまたはparam2の値を持っていませBaseChildChild。これが理にかなっていることを願っています!.

4

1 に答える 1

1
// define the Base Class
function Base() {
   // your awesome code here
}

// define the BaseChild class
function BaseChild() {
  // Call the parent constructor
  Base.call(this);
}

// define the Child class
function Child() {
  // Call the parent constructor
  BaseChild.call(this);
}


// inherit Base
BaseChild.prototype = new Base();

// correct the constructor pointer because it points to Base
BaseChild.prototype.constructor = BaseChild;

// inherit BaseChild
Child.prototype = new BaseChild();

// correct the constructor pointer because it points to BaseChild
Child.prototype.constructor = BaseChild;

Object.createを使用した代替アプローチ

BaseChild.prototype = Object.create(Base.prototype);
Child.prototype = Object.create(BaseChild.prototype);
于 2013-08-07T09:35:56.657 に答える