原型问题1—原型对象的替换

function Animal(){
    this.type = "Animal"; 
}
 Animal.prototype.say = function(){
     console.log(this.type); 
}
 function Cat(){
       this.vioce = "喵喵喵"; 
} 
Cat.prototype.shout = function(){ 
console.log(this.vioce);
 } 
Cat.prototype = new Animal();

 let cat1 = new Cat();
 cat1.say(); //"Animal" 
cat1.shout(); //err,报错无此函数

为什么cat1.shout会找不到因为:

Cat.prototype.shout = function(){ console.log(this.vioce); } 
已经为Cat.prototype 指向了一个对象{    shout = function(){ console.log(this.vioce); }   }

所以Cat.prototype  = new Animal()

会重新把Cat.prototype的指向更改为{ new Cat() }对象;

所以会找不到:

解决办法:

先 Cat.prototype  = new Animal() 创建一个指向,

然后:Cat.prototype.shout = function(){ console.log(this.vioce); }  这一步是给对象{ new Animal() } 添加了一个属性

原文地址:https://www.cnblogs.com/jokes/p/9233259.html