1.通过原型继承
//例
//动物的构造函数
function Animal(name,weight) {
this.name = name ;
this.weight = weight;
}
//动物的原型方法
Animal.prototype.eat = function(){
console.log("天天吃东西,就是吃");
}
//狗的构造函数
function Dog(color) {
this.color = color;
}
// 继承
//狗继承动物的构造函数
Dog.prototype = new Animal("哮天犬","50kg");
//狗咬人
Dog.prototype.bitePerson = function(){
console.log("汪汪");
}
//哈士奇
function ErHa(sex){
this.sex =sex;
}
//二哈继承狗的颜色
ErHa.prototype = new Dog("黑白色");
ErHa.prototype.playHost=function(){
console.log("ASIKLDVJMgl;knvmk");
}
// 输出看结果
var erha = new ErHa("雄性");
console.log(erha.name,erha.weight,erha.color);
erha.eat();
erha.bitePerson();
erha.playHost();
动物(父级) ==> 狗(子级) ==> 哈士奇(孙子级)
2、组合继承
function Food(name,age,tag){
this.name = name;
this.age = age;
this.tag = tag;
}
Food.prototype.liit = function(){
console.log("hhhh");
}
function Cggod(name,age,tag,color){
// 借用构造函数
Food.call(this,name,age,tag,color);
this.color = color;
}
Cggod.prototype = new Food();//不传值,用来解决原型调用的问题
//顺序不要写反了
Cggod.prototype.tat = function(){
console.log("mmmmm");
}
//输出结果
var cggod = new Cggod("小张","男","18","黄色");
console.log(cggod.name);
cggod.liit();
cggod.tat();
var cggod2 = new Cggod("小张","男","18","黄色");
console.log(cggod2.name);
cggod2.liit();
cggod2.tat();
3、拷贝继承
(浅拷贝)
function Loop(){
}
Loop.prototype.name = "zhang";
Loop.prototype.sex = "nan";
Loop.prototype.height = "178";
Loop.prototype.play = function(){
console.log("玩的好开心");
};
var obj2 = {};
// fon--in循环拷贝
for(var key in Loop.prototype){
obj2[key] = Loop.prototype[key];
}
console.dir(obj2);
obj2.play();