zoukankan      html  css  js  c++  java
  • Javascript继承1:子类的的原型对象----类式继承

    //声明父类
    function Parent(){
        this.parentValue = true;
        this.favorites = ['看书']
    }
    //为父类添加公有方法
    Parent.prototype.getParentValue = function(){
        return this.parentValue;
    }
    //声明子类
    function Child(){
        this.childValue = false;
    }
    // 继承父类
    Child.prototype =  new Parent()
    //为子类添加方法
    Child.prototype.getChildValue = function(){
        return this.childValue;
    }
    
    var instance = new Child()
    console.log(instance.getParentValue())  //true
    console.log(instance.getChildValue())   //false
    /*
    *注:使用instanceof检测某个对象是否是某个某个类的实例,
    *    或者说某个对象是否继承了某个类
    */
    console.log(instance instanceof Parent) //true
    console.log(instance instanceof Child)  //true
    console.log(Child instanceof Parent)    //false 为何?Child的原型继承了父类
    
    console.log(Child.prototype instanceof Parent) //true
    /*
    *缺点:一个子类改变继承于父类的公有属性,其他子类会受到影响
    *    如何避免??下一小节
    */
    var child1 = new Parent()
    var child2 = new Parent()
    console.log(child2.favorites) //['看书']
    child1.favorites.push('旅游')
    console.lof(child2.favorites) //['看书','旅游']

    设计模式中的经典笔录

  • 相关阅读:
    mysql实现主从备份
    Spring boot 继承 阿里 autoconfig 配置环境参数
    Spring Boot 注解的使用
    SpringBoot yml 配置
    浅谈提高工作效率
    Oracle 数据库特殊查询总结
    WPF MVVM 学习总结(一)
    VS2010部署Asp.net程序到本地IIS 7
    Asp.net MVC3表格共用分页功能
    WCF学习总结
  • 原文地址:https://www.cnblogs.com/-walker/p/9737375.html
Copyright © 2011-2022 走看看