1.原型继承
原型继承不需要使用类来定义对象的结构,直接定义对象,并被其他对象所引用,形成一种继承关系。
原型继承可以继承添加给父类的方法
function Animal(name){
this.name="Animal";
this.eat=function(){
return "吃食物!"
}
}
//给Animal添加方法
Animal.prototype.sleep= function () {
return this.name+"正在睡觉!"
}
function cat(){
}
cat.prototype=new Animal();//原型对象继承Animal的实例
cat.prototype.name="猫";
var c=new cat()//实例化cat
console.log(c.name);//猫
console.log(c.eat());//吃食物!
console.log(c.sleep())//猫正在睡觉
2.构造继承:子类实例
instanceof用来测试一个对象在原型链中是否存在一个构造函数
call(传值是以参数列表形式传值)
apply(传值是以数组方式传值)
function Animal(name){
this.name=name||"Animal";
this.eat=function(){
return "吃食物!"
}
}
Animal.prototype.sleep= function () {
return this.name+"正在睡觉!"
}
function cat(){
Animal.call(this,"猫");//在当前对象中调用Animal,并传参给Animal
}
var c=new cat();
console.log(c.name);
console.log(c.eat());
/!*console.log(c.sleep())//只可以继承父类本身所带属性,添加的属性无法继承
console.log(c instanceof cat);//true
console.log(c instanceof Animal);//false;c的原型链中不存在Animal
3.实例继承:不是子类的实例,而是父类的实例
原型链继承和构造继承在客户端中无法继承DOM对象,同时它们也不支持继承系统对象和方法
function Animal(name){
this.name=name||"Animal";
this.eat=function(){
return "吃食物!"
}
}
function cat(){//在子类中实例化父类
var animal=new Animal();
animal.name="猫";
return animal;
}
var c=new cat();
console.log(c.name);//猫
console.log(c.name+c.eat());//猫吃食物
4.组合继承
使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承
组合继承避免了原型链和借用构造函数的缺点,融合了他们的优点,成为JAVASCRIPT中最常用的继承方式.
function Animal(name){
this.name="Animal" || name;
this.eat=function (){
return this.name+"正在吃饭!";
}
}
//添加方法:prototype 属性使您有能力向对象添加属性和方法。
Animal.prototype.sleep= function () {
return this.name+"正在睡觉!"
}
//定义子类,并且在子类中用Animal替代this对象,cat中就拥有了Animal的属性和方法了
function cat(){
Animal.call(this,"猫");
}
cat.prototype=new Animal();//利用原型继承可以使用父类的方法
var c=new cat();//实例化子类
console.log(c.name);
console.log(c.eat());
console.log(c.sleep())
console.log(c instanceof Animal)//true
console.log(c instanceof cat)//true:c的原型链中存在cat