zoukankan      html  css  js  c++  java
  • 面向对象的程序设计(四)原型链继承

    function SuperType() {
        this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function () {
        return this.property;
    }
    
    function SubType() {
        this.subproperty = false;
    }
    
    //继承了SuperType
    SubType.prototype = new SuperType();
    
    SubType.prototype.getSubValue = function () {
        return this. subproperty;
    }
    
    var instance = new SubType();
    alert(instance.getSuperValue());//true
    
    alert(instance instanceof Object);//true
    alert(instance instanceof SubType);//true
    alert(instance instanceof SuperType);//true
    
    alert(Object.prototype.isPrototypeOf(instance));//true
    alert(SubType.prototype.isPrototypeOf(instance));//true
    alert(SuperType.prototype.isPrototypeOf(instance));//true
    
    //SubType继承了SuperType,通过创建SuperType的实例。
    //弊端1:看下面的列子,instance3的colors属性居然被instance2改变了
    //弊端2:没有办法在不影响所有对象实例的情况下,给超类型构造函数(SuperType2)传递参数
    function SuperType2() {
        this.colors = ["red", "blue"];
    }
    
    function SubType2() {
    }
    
    SubType2.prototype = new SuperType2();
    
    var instance2 = new SubType2();
    instance2.colors.push("black");
    alert(instance2.colors);//"red", "blue", "black"
    
    var instance3 = new SubType2();
    alert(instance3.colors);//"red", "blue", "black"
  • 相关阅读:
    [ZJOI2011]营救皮卡丘
    TJOI2018Party
    HEOI2013SAO
    [BJOI2017]树的难题
    [HNOI2016]序列
    [SHOI2007]善意的投票
    CF802C Heidi and Library (hard)
    SPOJ DIVCNT2
    LOJ子序列
    BZOJ2882工艺
  • 原文地址:https://www.cnblogs.com/qiangspecial/p/3175233.html
Copyright © 2011-2022 走看看