JavaScript继承

2018-06-19  本文已影响0人  helloyoucan

1.原型链

function SuperType(){     
  this.property = true; 
} 
SuperType.prototype.getSuperValue = function(){     
  return this.property; 
}; 
function SubType(){     
  this.subproperty = false; 
} 
//继承了 SuperType 
SubType.prototype = new SuperType(); 
 
SubType.prototype.getSubValue = function (){     
  return this.subproperty; 
}; 
 
var instance = new SubType(); 
alert(instance.getSuperValue());      //true 

2.借用构造函数

function SuperType(){     
  this.colors = ["red", "blue", "green"]; 
} 

function SubType(){       
  //继承了 SuperType     
  SuperType.call(this); 
} 

var instance1 = new SubType(); 
instance1.colors.push("black"); 
alert(instance1.colors);    //"red,blue,green,black" 
 
var instance2 = new SubType(); 
alert(instance2.colors);    //"red,blue,green"

3.组合继承

function SuperType(name){     
  this.name = name;     
  this.colors = ["red", "blue", "green"]; 
} 
 
SuperType.prototype.sayName = function(){     
  alert(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(){     
  alert(this.age); 
}; 
 
var instance1 = new SubType("Nicholas", 29); 
instance1.colors.push("black"); 
alert(instance1.colors);      //"red,blue,green,black" 
instance1.sayName();          //"Nicholas"; 
instance1.sayAge();           //29 
 
var instance2 = new SubType("Greg", 27); 
alert(instance2.colors);      //"red,blue,green" 
instance2.sayName();          //"Greg"; 
instance2.sayAge();           //27 
 

4.原型式继承

var person = {     
  name: "Nicholas",     
  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"); 
 
alert(person.friends); //"Shelby,Court,Van,Rob,Barbie" 

5.寄生式继承

function createAnother(original){     
  var clone = object(original);  //通过调用函数创建一个新对象     
  clone.sayHi = function(){      //以某种方式来增强这个对象         
    alert("hi");     
  };    
  return clone;         //返回这个对象 
} 
var person = {     
  name: "Nicholas",     
  friends: ["Shelby", "Court", "Van"] 
}; 
 
var anotherPerson = createAnother(person); 
anotherPerson.sayHi(); //"hi"

6.寄生组合式继承

function SuperType(name){     
  this.name = name;     
  this.colors = ["red", "blue", "green"]; 
} 
 
SuperType.prototype.sayName = function(){     
  alert(this.name); 
}; 
 
function SubType(name, age){       
  SuperType.call(this, name);         //第二次调用 SuperType()          
  this.age = age; 
} 
 
SubType.prototype = new SuperType();    //第一次调用 SuperType()
SubType.prototype.constructor = SubType; 
SubType.prototype.sayAge = function(){     
  alert(this.age); 
}; 

未续待完...

上一篇下一篇

猜你喜欢

热点阅读