继承的几种方法及优缺点

1.构造函数继承

function Cat(name,color){
    this.name = name;
    this.color = color;
    this.type = "猫科动物";
    this.eat = function(){alert("吃老鼠");};
}
var cat1=new Cat("花花","白色");
console.log(cat1.type);//猫科动物

cat1会自动含有一个construtor属性,指向它们的构造函数:alert(cat1.constructor == Cat); //true

Javascript还提供了一个instantanceof运算符,验证原型对象与实例对象之间的关系:alert(cat1 instanceof Cat); //true

缺点:浪费内存 (type属性和eat()方法都是一模一样的内容,每一次生成一个实例,都必须为重复的内容,多占用一些内存)

function Animal(){
    this.species = "猫科动物";
}
function Cat(name,color){
    Animal.apply(this, arguments);//Cat继承Animal
    this.name = name;
    this.color = color;
}
var cat1 = new Cat("花花","白色");
alert(cat1.species); //猫科动物

apply、call 和 bind 方法继承: http://www.cnblogs.com/mina-huojian66/p/6097808.html 

2.Prototype模式继承

Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。

function Animal(){
  this.type="猫科动物";
}
function
Cat(name,color){     this.name = name;     this.color = color; }
方法一: Cat.prototype.type
= "猫科动物"; Cat.prototype.eat = function(){alert("吃老鼠")}; var cat1=new Cat("花花","白色"); console.log(cat1.type);//猫科动物
console.log(cat1.eat());//吃老鼠
方法二:
Cat.prototype = new Animal();//Cat.prototype.constructor指向Anmail,也指向cat
console.log(
Cat.prototype.constructor==Animal);//true
console.log(Cat.prototype.constructor==Cat);//true
Cat.prototype.condtructor=Cat;
var cat1=new Cat("花花","白色");
console.log(cat1.type);//猫科动物
方法三:
Cat.prototype=Animal.prototype;
Cat.prototype.constructor=Cat;
var cat1=new Cat("花花","白色");
console.log(cat1.type);//猫科动物

 Prototype模式的验证方法

a.alert(Cat.prototype.isPrototypeOf(cat1)); //true

b.alert(cat1.hasOwnProperty("name")); // true

c.alert("name" in cat1); // true

 缺点: Cat.prototype和Animal.prototype现在指向了同一个对象,那么任何对Cat.prototype的修改,都会反映到Animal.prototype。

Cat.prototype.constructor = Cat;

alert(Animal.prototype.constructor); // Cat

方法四:利用空对象作为中介
var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;
alert(Animal.prototype.constructor); // Animal

//封装
function jicheng(Child,Parent){
  var F=function(){};
  F.prototype=Parent.prototype;
  Child.prototype=new F();
  Child.prototype.construction=Child;
}
jicheng(Cat,Animal);
var cat1=new Cat("花花","白色");
console.log(cat1.type);//猫科动物

大部分学习于:http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance.html

posted @ 2016-11-24 17:31  米娜-火箭  阅读(293)  评论(0编辑  收藏  举报