• 面向对象的程序设计(四)原型链继承


    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"
  • 相关阅读:
    【面试题】M
    【转】C/S,B/S区别
    【转】指针和引用的区别
    内联函数
    实习-随记
    【面试】http协议知识
    wenbenfenlei
    【面试】链表反转
    测试面试题2
    测试面试题
  • 原文地址:https://www.cnblogs.com/qiangspecial/p/3175233.html
Copyright © 2020-2023  润新知