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("泰迪","10kg");
//先改变原型指向,再创建新的方法
Dog.prototype.bitePerson=function(){
console.log("汪汪")
}
var dog=new Dog("黄色");
console.log(dog.name,dog.weight,dog.color)
dog.eat()
dog.bitePerson()```
#####2.借用构造函数实现继承,不能继承方法
```//动物的构造函数
function Animal(name,weight){
this.name=name;
this.weight=weight;
}
//狗的构造函数
function Dog(name,weight,color){
//1、借用构造函数 (call方法)
//Animal.call(this,name,weight)
//2、借用构造函数 (apply方法)
Animal.apply(this,arguments)
this.color=color;
}
var dog=new Dog("泰迪","10kg","黄色");
console.log(dog.name,dog.weight,dog.color)```
#####3.组合继承(改变原型的指向+借用构造函数)
```//动物的构造函数
function Animal(name,weight){
this.name=name;
this.weight=weight;
}
Animal.prototype.eat=function(){
console.log("天天吃东西")
}
//狗的构造函数
function Dog(name,weight,color){
//借用构造函数
Animal.call(this,name,weight)
this.color=color;
}
//改变原型指向
Dog.prototype=new Animal();
Dog.prototype.bitePerson=function(){
console.log("汪汪")
}
var dog=new Dog("泰迪","10kg","黄色");
console.log(dog.name,dog.weight,dog.color)
dog.eat()
dog.bitePerson()```
#####4.拷贝继承,把一个对象中的原型的所有属性和方法复制一份给另一个对象(浅拷贝)
```function Animal(){
}
Animal.prototype.name="泰迪"
Animal.prototype.weight="10kg"
Animal.prototype.eat=function(){
console.log("天天吃东西")
}
var animalObj={}
for(var key in Animal.prototype){
if(animalObj[key]==undefined){
animalObj[key]=Animal.prototype[key]
}
}
console.log(animalObj.name,animalObj.weight)
animalObj.eat()