对象继承: 实例化对象给可以继承object(对象)的内容 不能继承函数的内容
原型继承:子类继承父类,让子类的原型指向父类
子类.prototype =new 父类()
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('白小黑','18')
Dog.prototype.bitePerson = function(){
console.log('咬人');
}
function ErHa(sex){
this.sex = sex
}
ErHa.prototype = new Dog('黑色')
ErHa.prototype.playHost = function(){
console.log('玩');
}
拷贝继承:指深拷贝,深拷贝:拷贝值 浅拷贝:拷贝地址
for (x in p1) {
// 只需要拷贝属性值即可
stu1[x] = p1[x];
}
var animal = new Animal('大象','18')
var tiger = new Tiger('母老虎')
for(key in animal){
tiger[key] = animal[key]
}
tiger.eat()
console.log(tiger);
构造函数继承: call() 方法改变this指向,将父类.call(this,属性) 写到子类的构造函数中使this指向子类构造函数的实例化对象
function Animal(name, weight, age, sex) {
this.name = name;
this.weight = weight;
this.age = age;
this.sex = sex;
this.eat = function () {
console.log('吃骨头');
}
}
Animal.prototype.play = function () {
console.log('玩耍');
}
function Cat(color, name, weight, age, sex) {
this.color = color
Animal.call(this, name, weight, age, sex);
}
var cat = new Cat('白色', '小白', '18公斤', 18, '公猫')