js繼承的幾種方式

原型鏈繼承:沒法傳參app

function Fun1(){

  this.property = true;

}

Fun1.prototype.getValue = function(){

  return this . property;

}

Function Fun2(){

  this.sub = false;

}

Fun2.prototype = new Fun1();

Fun2.prototype .sayValue = function(){

  return this.sub;

}

Var instance = new Fun2();

Console.log(instance.getValue());

// 建立Fun1的實例,並講該實例賦給Fun2.prototype實現的。本質是重寫原型對象,代之以一個新類型的實例。原來存在於Fun1的實例中的屬性和方法,如今也存在於Fun2.prototype中了。

 

構造函數call() apply()  解決傳參的問題,父類原型的屬性和方法不能繼承,實例不是父類的實例函數

function Fun1(){

  this.color=[‘red’ , ’blue’];

}

function Fun2(){

  fun1.call(this);

}

var instance1 = new Fun2();

Instance1.colors.push(「black」);

Console.log(instance1.colors); //red blue black

 

Var instance2 = new Fun2();

Console.log(instance2.colors); // red blue

 

傳參:

Function Fun1(name){

  this.name = name;

}

Function Fun2(age){

Fun2.call(this, 「John」);

  This.age = 23;

}

Var instance = new Fun2();

Console.log(instance.name)// John

Console.log(instance.age)//23

 

 

組合繼承:組合原型鏈和構造函數,原型鏈實現對原型屬性和方法的繼承,構造函數來實現對實例屬性的繼承。this

Function Fun1(name){

This.name = name;

This.color = [「red」 , 「blue」];

}

Fun1.prototype.sayName = function(){

alert(this.name);

}

Function Fun2(name , age){

Fun1.call(this , name);

This.age = age;

}

Fun2.prototype = new Fun1();

Fun2.prototype.sayAge = function(){

Console.log(this.age);

}

Var instance1= new Fun2(「John」, 29);

Instance1.colors.push(「black」);

Console.log(instance1.colors); //red blue black

Instance1.sayName (); //John

Instance1.sayAge(); // 29

 

Var instance2 = new Fun2();

Console.log(Instance2.color); //red blue

Instance.sayName();//John

Instance.sayAge(); //29

 

原型式繼承:藉助原型能夠基於已有的對象建立新對象,同時還沒必要須所以建立自定義的類型。spa

 

//新增Object.create()方法規範了原型式繼承
//能夠傳遞兩個參數,第一個是用做新對象原型的對象,第二個(可選)爲新對象定義額外屬性的對象

//傳遞一個參數時,等同於object()
var person = {
  name:"EvanChen",
  friends:["Shelby","Court","Van"];
};
 var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
 
var yetAnotherPerson = Object.create(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
 
console.log(person.friends);//"Shelby","Court","Van","Rob","Barbie"
思想:

function object(o) {

  function F(){ }

  F.prototype = o;

  return new F();

}

var person = {
    name:"EvanChen",
    friends:["Shelby","Court","Van"];
};
var anotherPerson = object(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");

var yetAnotherPerson = object(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");

console.log(person.friends);//"Shelby","Court","Van","Rob","Barbie"
//必須有一個對象做爲另外一個對象的基礎,若是有這麼一個對象的話,能夠傳遞給object()函數,而後該函數就會返回一個新的對象
相關文章
相關標籤/搜索