码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-06-27 14:03:36      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:pre   一个   this   这一   class   IV   nim   cat   func   

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.shuot(); //err,报错无此函数

为什么cat1会找不到因为:

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() } 添加了一个属性

 

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

标签:pre   一个   this   这一   class   IV   nim   cat   func   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!