• 原型问题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() } 添加了一个属性

  • 相关阅读:
    MySQL常用团队开发规范
    X进制
    MySQLJDBC
    Centos安装MongoDB
    log4php PHP 的日志框架
    20220512 08:00:02
    JS/TS笔记(仅语言层面的)
    聊聊我们是如何做技术保障的
    20220512 08:00:02
    Github不稳定的解决办法
  • 原文地址:https://www.cnblogs.com/jokes/p/9233259.html
Copyright © 2020-2023  润新知