js繼承的6種方法


1.原型鏈繼承

JavaScript實現繼承的基本思想:通過原型將一個引用類型繼承另一個引用類型的屬性和方法。

實例:

function Test(){
  this.name='alan';
}
Test.prototype.demo = function(){//----增加demo方法
  return 'test';
}
function TestDemo(){}
TestDemo.prototype = new Test();//----將Test實例賦給TestDemo的原型對象
var a = new TestDemo();
a.name; //------->alan
a.demo(); //------->test  TestDemo的實例能訪問到Test對象的實例方法,也能訪問到其原型屬性中的方法。

 

2.借用構造函數繼承(偽造對象或經典繼承)

JavaScript實現繼承的基本思想:在子類構造函數內部調用超類型構造函數。

通過使用apply()和call()方法可以在新創建的子類對象上執行構造函數。

實例: 

function Test(){
  this.names=['alan','tony','lucy']
}
function TestDemo(){
  Test.apply(this);//---->繼承了Test
}
var a = new TestDemo();
a.names.push('alice');
console.log(a.names);//---->alan,tony,lucy,alice
var b = new TestDemo();
console.log(b.names);//---->alan,tony,lucy

  

3.組合繼承(原型+借用構造)(偽經典繼承)

JavaScript實現繼承的基本思想:將原型鏈和借用構造函數的技術組合在一塊,從而發揮兩者之長的一種繼承模式。

將原型鏈和借用構造函數的技術組合到一起,從而取長補短發揮兩者長處的一種繼承模式。

實例:

function Test(name){
  this.colors = ['red','blue','black']; 
  this.name = name;
}
Test.prototype.HiName = function(){
  console.log(this.name);
}
function TestDemo(){
  Test.call(this,name);//---->屬性繼承
}

//---->繼承方法
TestDemo.prototype = new Test();
TestDemo.prototype.constructor = TestDemo;
TestDemo.prototype.HiAge = function() {
  console.log(this.age);
}

var a = new TestDemo('alan',18);
a.colors.push('green');
consol.log(a.colors);//---->red,blue,black,green
a.HiName();//---->alan
a.HiAge();//---->18
var b = new TestDemo('alan6',20);
console.log(b.colors);//---->red,blue,black
b.HiName();//---->alan6
b.HiAge();//---->20

 

4.原型式繼承

JavaScript實現繼承的基本思想:借助原型可以基於已有的對象創建新對象,同時還不必須因此創建自定義的類型。

實例: 

var Test =  {
  name:'alan',
  colors:['red',blue,'black'];
}
var aTest = object(Test);
aTest.name = 'lucy';
aTest.colors.push('green');
var bTest = object(Test);
bTest.name = 'tony';
bTest.colors.push('grey');
console.log(Test.colors);//---->red,blue,black,green,grey

 

5.寄生式繼承

JavaScript實現繼承的基本思想:創建一個僅用於封裝繼承過程的函數,該函數在內部以某種方式來增強對象,最后再像真正是它做了所有工作一樣返回對象。

寄生式繼承是原型式繼承的加強版。

實例:

function Test(orig){
  var clone = object(orig);
  clone.a = function(){
    console.log('alan');
  }
  return clone;
}
var TestDemo = {
  name = 'lucy';
  colors:['red','blue','black'];  
}
var abc = Test(TestDemo);
abc.a;//---->alan

 

6.寄生組合式繼承

JavaScript實現繼承的基本思想:通過借用函數來繼承屬性,通過原型鏈的混成形式來繼承方法。

基本模型:

function inheritProperty(subType, superType) {
  var prototype = object(superType.prototype);//---->創建對象
  prototype.constructor = subType;//---->增強對象
  subType.prototype = prototype;//---->指定對象
}

實例:

function Test(name){
    this.name = name;
    this.colors = ['red','blue','black'];
}
Test.prototype.sayName = function (){
    alert(this.name);
};
function TestDome(name,age){
    Test.call(this,name);
    this.age = age;
}
inheritProperty(Test,TestDome);
    TestDome.prototype.sayAge = function() {
    console.log(this.age);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM