首页 > 其他 > 详细

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

时间:2018-06-27 12:44:24      阅读:305      评论:0      收藏:0      [点我收藏+]
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—原型对象的替换

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!