JAvascript学習ノート(10)jsオブジェクト継承

4202 ワード

1.プロトタイプチェーン
//単独での使用は少ない
 
  
View Code
// SuperClass , property getSuperValue
function SuperClass() {
this.property = true;
}
SuperClass.prototype.getSuperValue = function() {
return this.property;
}

// SubClass , subproperty getSubValue
function SubClass() {
this.subproperty = false;
}

//SubClass SuperClass
SubClass.prototype = new SuperClass();

//SubClass getSubValue
SubClass.prototype.getSubValue = function() {
return this.subproperty;
}

// SubClass
var instance = new SubClass();
alert(instance.getSuperValue());

2.プロトタイプとインスタンスの関係の決定
1つ目の方法はinstanceofオペレータを使用して、インスタンスとプロトタイプチェーンに現れた構造関数をテストします.
 
  
alert(instance instanceof Object); //true ,instance Object ?
alert(instance instanceof SuperClass); //true ,instance SuperClass ?
alert(instance instanceof SubClass); //true,instance SubClass ?

2つ目の方法はisPrototypeOf()法を用いてプロトタイプチェーンに現れるプロトタイプをテストする
 
  
alert(Object.prototype.isPrototypeOf(instance)); //true
alert(SuperClass.prototype.isPrototypeOf(instance)); //true
alert(SubClass.prototype.isPrototypeOf(instance)); //true

3.プロトタイプチェーンで定義方法を継承する際の注意点
メソッドの順序を定義します.
 
  
View Code
function SuperClass() {
this.property = true;
}
SuperClass.prototype.getSuperValue = function() {
return this.property;
}

function SubClass() {
this.subproperty = false;
}

//SubClass SuperClass
SubClass.prototype = new SuperClass(); // , ,

//
SubClass.prototype.getSubValue = function() {
return this.subproperty;
}
//
SubClass.prototype.getSuperValue = function() {
return false;
}
var instance = new SubClass();
alert(instance.getSuperValue()); //fales, SubClass SubClass getSuperValue() , SuperClass getSuperValue() ,
// SuperClass SuperClass getSuperValue()

プロトタイプチェーン継承の欠点:1)スーパークラスの属性を共有し,2)サブクラスの作成時にスーパークラスの構造関数にパラメータを渡すことができない.プロトタイプチェーンを単独で使用することはほとんどありません
4.借用構造関数
//単独での使用は少ない
利点:パラメータをスーパークラスに渡すことができます.欠点:関数は多重化できません.すべてのクラスで構造関数モードを使用します.
 
  
View Code
function SuperClass(name) {
this.name = name;
}
function SubClass(){
SuperClass.call(this,"RuiLiang"); // SuperClass, SuperClass
this.age = 29; //
}

var instance = new SubClass();
alert(instance.name); //RuiLiang
alert(instance.age); //29

6.組合せ継承
//最も一般的な継承パターン
 
  
View Code
// SuperClass
function SuperClass(name) {
this.name = name;
this.colors = ["red","blue","green"];
}
SuperClass.prototype.sayName = function() {
alert(this.name);
}

//// SubClass
function SubClass(name,age) {
SuperClass.call(this,name); //
this.age = age; //
}

SubClass.prototype = new SuperClass(); //
SubClass.prototype.sayAge = function() { //SubClass
alert(this.age);
};

//
var instance1 = new SubClass("RuiLiang",30);
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
instance1.sayName(); //"RuiLiang"
instance1.sayAge(); //30

var instance2 = new SubClass("XuZuNan",26);
alert(instance2.colors); //"red,blue,green"
instance2.sayName(); //"RuiLiang"
instance2.sayAge(); //30

7.その他の継承モード
プロトタイプ継承、寄生式継承、寄生組合せ式継承