面对对象继承之原型链继承

来源:互联网 发布:我要当学霸 知乎 编辑:程序博客网 时间:2024/05/16 04:28

面对对象继承之原型链继承


//构造函数继承的特点/缺点 :所有的属性都是对象独有,不能共享
//对象属性可以共性属性
function Animal() {
this.species = "动物";
this.eat = function() {
alert("吃吃吃...");
}
this.name = "动物名";//实例属性,每个动物都应该不一样
}


//Animal的原型属性
Animal.prototype.shake = function() {
alert("摇一摇");
}


//猫
function Cat(color){
//让Cat获得所有的实例属性,这些属性不需要共享
Animal.call(this);
this.cail = "尾巴";
this.color = color;
this.scream = function() {
alert("喵喵喵...");
};
this.catchMouse = function() {
alert("抓老鼠...");
}
}



//var m1 = new Cat("小黄");
//console.log(m1);//Cat {species: "动物", name: "动物名", cail: "尾巴", color: "小黄"}
//alert(m1.__proto__ === Cat.prototype);//true



//让Cat的原型指向一个Aniaml对象,从而所有的Cat对象都从原型中获得了共享的属性
//Cat原型的对象获取了一个Animal对象的值 可以在不同的Cat对象中共享
//new Animal()是一个动物对象,包含对象的实例属性和原型属性
Cat.prototype= new Animal();
var m1 = new Cat("小红");
m1.eat();//m1本身没有eat 从__proto__中找(Cat.prototype)
m1.shake();
var m2 = new Cat("小黑");
///通过原型属性继承过来的属性都是共享的,name属性不应该共享,Cat名不一样
alert(m2.name);
alert(m1.name);


//m1调用shake时,m1本身中没有shake 则会去Cat的原型中找
//Cat的原型(是一个Animal对象),继承是通过原型链实现的,所有的Cat对象共享
console.log(m1);//Cat {species: "动物", name: "动物名", cail: "尾巴", color: "小红"}

//对象属性可以共性属性
function Animal() {
this.species = "动物";
this.eat = function() {
alert("吃吃吃...");
}
this.name = "动物名";//实例属性,每个动物都应该不一样
}


//Animal的原型属性
Animal.prototype.shake = function() {
alert("摇一摇");
}


//猫
function Cat(color){
//让Cat获得所有的实例属性,这些属性不需要共享
Animal.call(this);
this.cail = "尾巴";
this.color = color;
this.scream = function() {
alert("喵喵喵...");
};
this.catchMouse = function() {
alert("抓老鼠...");
}
}



//var m1 = new Cat("小黄");
//console.log(m1);//Cat {species: "动物", name: "动物名", cail: "尾巴", color: "小黄"}
//alert(m1.__proto__ === Cat.prototype);//true



//让Cat的原型指向一个Aniaml对象,从而所有的Cat对象都从原型中获得了共享的属性
//Cat原型的对象获取了一个Animal对象的值 可以在不同的Cat对象中共享
//new Animal()是一个动物对象,包含对象的实例属性和原型属性
Cat.prototype= new Animal();
var m1 = new Cat("小红");
m1.eat();//m1本身没有eat 从__proto__中找(Cat.prototype)
m1.shake();
var m2 = new Cat("小黑");
///通过原型属性继承过来的属性都是共享的,name属性不应该共享,Cat名不一样
alert(m2.name);
alert(m1.name);



0 0