1.通過原型實(shí)現(xiàn)繼承辣卒,改變?cè)偷闹赶蛄彰ǎ跏蓟鄠€(gè)對(duì)象時(shí)屬性值一樣
function Animal(name,weight){
this.name=name;
this.weight=weight;
}
Animal.prototype.eat=function(){
console.log("天天吃東西")
}
//狗的構(gòu)造函數(shù)
function Dog(color){
this.color=color;
}
//改變?cè)偷闹赶?實(shí)現(xiàn)繼承
Dog.prototype=new Animal("泰迪","10kg");
//先改變?cè)椭赶颍賱?chuàng)建新的方法
Dog.prototype.bitePerson=function(){
console.log("汪汪")
}
var dog=new Dog("黃色");
console.log(dog.name,dog.weight,dog.color)
dog.eat()
dog.bitePerson()```
#####2.借用構(gòu)造函數(shù)實(shí)現(xiàn)繼承,不能繼承方法
```//動(dòng)物的構(gòu)造函數(shù)
function Animal(name,weight){
this.name=name;
this.weight=weight;
}
//狗的構(gòu)造函數(shù)
function Dog(name,weight,color){
//1瓶佳、借用構(gòu)造函數(shù) (call方法)
//Animal.call(this,name,weight)
//2桌粉、借用構(gòu)造函數(shù) (apply方法)
Animal.apply(this,arguments)
this.color=color;
}
var dog=new Dog("泰迪","10kg","黃色");
console.log(dog.name,dog.weight,dog.color)```
#####3.組合繼承(改變?cè)偷闹赶?借用構(gòu)造函數(shù))
```//動(dòng)物的構(gòu)造函數(shù)
function Animal(name,weight){
this.name=name;
this.weight=weight;
}
Animal.prototype.eat=function(){
console.log("天天吃東西")
}
//狗的構(gòu)造函數(shù)
function Dog(name,weight,color){
//借用構(gòu)造函數(shù)
Animal.call(this,name,weight)
this.color=color;
}
//改變?cè)椭赶?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.拷貝繼承蒸绩,把一個(gè)對(duì)象中的原型的所有屬性和方法復(fù)制一份給另一個(gè)對(duì)象(淺拷貝)
```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()