2013-04-08 15 views
7

におけるクラスの継承は、以下の例をチェックしてみてください。呼び出し、基本クラスの機能はJavaScript

クラスMyBaseClassを継承できる必要がありますが、新しいinit()メソッドの開始時にinit()メソッドを呼び出すことができるようにする必要があります。

どうすればよいですか?

+3

'$ .extend'はあなたの考えをしません。 –

+1

このコードで目立った問題は、底に 'var'を使うことです。 –

+3

とにかく' $ .extend'とは何ですか? –

答えて

17

jQuery's extend"2つ以上のオブジェクトの内容を一緒に第1のオブジェクトに結合する"

使用prototype based inheritanceあなたの継承を実現し、明示的に "スーパー" メソッドを呼び出すために:

MyBaseClass = function(a) { 
    this.a = a; 
}; 
MyBaseClass.prototype.init = function() { 
    console.log('I am initializing the base class'); 
}; 

MyChildClass = function(a) { 
    this.a = a; 
} 
MyChildClass.prototype = Object.create(MyBaseClass.prototype); // makes MyChildClass "inherit" of MyBaseClass 
MyChildClass.prototype.init = function() { 
    MyBaseClass.prototype.init.call(this); // calls super init function 
    console.log('I am initializing the child class'); 
}; 

var child= new MyChildClass(); 
child.init(); 

Output:物事の

I am initializing the base class 
I am initializing the child class 
+0

ここで 'Object.create'を使うべきですか? –

+0

OPは「クラス」と継承について語っているので、私は個人的にプロトタイプが適していると感じています。 –

+2

Janは 'MyChildClass.prototype = Object.create(MyBaseClass.prototype);'を使うことを意図しているかもしれません。それは継承IMHOのためのより良いアプローチになります。親の新しいインスタンスをインスタンス化する*には欠点があります。 –

1

jsFiddle Demo

カップル。 extendは本当にプロパティを追加するだけですが、あまり効果がありません。だから、あなたのクラスの準備ができて、基底クラスから継承し、そのクラスのプロトタイプを拡張するための関数を持つ必要があります。ここで

function MyChildClass(){}; 
MyChildClass.prototype = new MyBaseClass(); 
$.extend(MyChildClass.prototype, { 
init: function() { 
    MyBaseClass.prototype.init(); 
    console.log('I am initializing the child class'); 
} 
}); 

は、私は、継承のために使用したい別のアプローチである - 独自のプロパティで

function MyChildClass(){}; 
MyChildClass.prototype = new MyBaseClass(); 
MyChildClass.prototype.base = new MyBaseClass(); 
$.extend(MyChildClass.prototype, { 
init: function() { 
    this.base.init(); 
    console.log('I am initializing the child class'); 
} 
}); 
1

別の基本クラスを格納することである - 方法の特異性が問題になるだろうされている場合

MyBaseClass = function(a) { 
    this.a = a; 
}; 

MyBaseClass.prototype = { 
    init: function() { 
     console.log('I am initializing the base class'); 
    } 
}; 

MyChildClass = function() {}; 
MyChildClass.prototype = $.extend(new MyBaseClass(), { 
    init: function() { 
     this.super.init.call(this); 
     console.log('init child'); 
    }, 
    super: MyBaseClass.prototype, 
    constructor: MyChildClass 
}); 

var a = new MyChildClass(); 
a.init(); 

出力:

プロトタイプベースのパターンは、この目標を達成するために10

this.superは、基本クラスへの参照を格納します。

+0

正直な質問:なぜあなたはコンストラクタを指定していますか? –

+0

@dystroy - jqueryソースコードで実際に見ました。私は時々コンストラクタが間違った関数を指していることがある(それを現時点で行うためには正確なシナリオを思い出すことができない)ためだと思います。 –

+0

@dystroy 'instanceof'を使用できるようにする。 'a instanceof MyChildClass' – dfsq

関連する問題