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) //['看书','旅游']

    设计模式中的经典笔录

  • 相关阅读:
    JAVA编程心得-JAVA实现CRC-CCITT(XMODEM)算法
    自学PHP 环境搭建
    Postfix+Amavisd-new+Spamassassin+ClamAV整合安装
    安装Apache Felix OSGI Framework小记
    C#多线程
    使用maven进行测试设置断点调试的方法
    2016第33周四
    Spring配置文件头及xsd文件版本
    2016第33周二
    web中的重定向与转发
  • 原文地址:https://www.cnblogs.com/-walker/p/9737375.html
Copyright © 2011-2022 走看看