歡迎您光臨本站 註冊首頁

JS中的繼承操作實例總結

←手機掃碼閱讀     retouched @ 2020-06-12 , reply:0

本文實例講述了JS中的繼承操作。分享給大家供大家參考,具體如下:

1.原型鏈繼承

  function SuperType() {    this.property = true;   }  SuperType.prototype.getSuperValue = function() {    return this.property;  }  function SubType() {    ths.subproperty = false;  }  SubType.prototype = new SuperType();   // 實現繼承  SubType.prototype.getSubValue = function() {    return this.subproperty;  }  var instance = new SubType();  console.log(instance.getSuperValue());   // true

 

原理:讓SuperType的實例成為子類的原型對象,子類的實例擁有了父類的屬性和方法。但也有弊端,如果父類的屬性是引用類型,這將導致共享的屬性被改變的時候,全部的屬性將被改變,我們一下代碼。

  function SuperType() {    this.property = [1,2,3];   }  SuperType.prototype.getSuperValue = function() {    return this.property;  }  function SubType() {    ths.subproperty = false;  }  SubType.prototype = new SuperType();   // 實現繼承  SubType.prototype.getSubValue = function() {    return this.subproperty;  }  var instance1 = new SubType();  var instance2 = new SubType();  instance1.property.push(4);  console.log(instance1.property);   // [1,2,3,4]  console.log(instance2.property);   // [1,2,3,4]

 

我們修改一處的實例屬性,兩個實例的屬性都會被修改,因為這個屬性是共享的,這也是原型鏈繼承的缺點。

2.構造函數繼承

  function SuperType(name) {    this.name = name;    this.numbers = [1,2,3];  }  function SubType() {    SuperType.call(this,"Nicholas");    this.age = 29;  }    var instance1 = new SubType();  var instance2 = new SubType();  instance1.property.push(4);  console.log(instance1.name);    // Nicholas  console.log(instance1.age);     // 29  console.log(instance1.numbers);   // [1,2,3,4]  console.log(instance2.numbers); // [1,2,3]

 

在子類中調用父類的構造函數,每次實例化時都會新建父類的屬性放在新實例中,因此每個實例中的屬性都是不一樣的,改變一個實例的值不會造成另一個實例的值改變。這個繼承方式的缺點是方法的定義不能複用。

3.組合繼承

這個方法將原型鏈繼承和構造函數繼承結合到一起,融合了他們各自的優點。

  function SuperType(name) {    this.name = name;    this.colors = ["red","blue","green"]  }  SuperType.prototype.sayName = function() {    console.log(this.name);  }  function SubType(name,age) {    SuperType.call(this,name);    this.age = age;  }  SubType.prototype = new SuperType();  SubType.prototype.constructor = SubType;  SubType.prototype.sayAge = function() {    console.log(this.age);  }    var instance1 = new SubType("Nicholas", 29);  var instance2 =new SubType("Greg", 27);  instance1.colors.push("black");  console.log(instance1.colors);    // red,blue,green,black  console.log(instance2.colors);    // red,blue,green  instance1.sayName();         // Nicholas  instance2.sayName();         // Greg  instance1.sayAge();           // 29  instance2.sayAge();           // 27

 

4.class繼承

ES6中可以通過class創建對象,通過關鍵字extends繼承。

  class Point {   constructor(x, y) {    this.x = x;    this.y = y;   }  }    class ColorPoint extends Point {   constructor(x, y, color) {    this.color = color; // ReferenceError    super(x, y);    this.color = color; // 正確   }  }

 

在ES6的繼承中,子類一定要重寫父類的構造函授的方法,否則會報錯。


[retouched ] JS中的繼承操作實例總結已經有277次圍觀

http://coctec.com/docs/javascript/show-post-238234.html