您的位置:首页 > 其它

面向对象继承一之经典继承

2016-11-03 21:55 120 查看
经典继承
     

//继承实现方案1:经典继承/构造函数继承,就是使用call调用父类的构造函数
//从而获得它的实例属性(直接写在构造函数中的属性)
//Cat 继承Animal
//所有的动物都有的特征
function Animal() {
this.species = "动物";
this.eat = function() {
alert("吃吃吃...");
}
}

function Cat(color) {
//猫有动物所具有的所有特征
Animal();//相当于window.Animal,此时的Animal是绑定到window对象的
Animal.call(this);//将Animal函数绑定到新建的Cat对象中
this.tail = "尾巴";
this.color = color;
this.scream = function() {
alert("喵喵喵...");
}
this.catchMouse = function() {
alert("抓老鼠...");
}
}

var m1 = new Cat("小黄");
console.log(m1);//Cat {species: "动物", tail: "尾巴", color: "小黄"}

//从而获得它的实例属性(直接写在构造函数中的属性)
//Cat 继承Animal
//所有的动物都有的特征
function Animal() {
this.species = "动物";
this.eat = function() {
alert("吃吃吃...");
}
}

function Cat(color) {
//猫有动物所具有的所有特征
Animal();//相当于window.Animal,此时的Animal是绑定到window对象的
Animal.call(this);//将Animal函数绑定到新建的Cat对象中
this.tail = "尾巴";
this.color = color;
this.scream = function() {
alert("喵喵喵...");
}
this.catchMouse = function() {
alert("抓老鼠...");
}
}

var m1 = new Cat("小黄");
console.log(m1);//Cat {species: "动物", tail: "尾巴", color: "小黄"}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: