zoukankan      html  css  js  c++  java
  • ECMAScript中的原型继承

    //ECMAScript中的原型继承
    //ECMAScript中的继承主要是依靠原型链实现的。(关于原型链的介绍,详见《高三》6.3.1章节 P162)

    //本文示例主要为了说明SubType.prototype=new SuperType()与SubType.prototype=SuperType.prototype的区别。
    //从理解的角度来说,它们的区别貌似就是把SubType.prototype原型指向了父类的实例对象与指向父类原型对象的区别,这似乎不难得出结论,
    //但是作为一个有原则有严谨态度的人,我觉得就还是有必要用实际行动来证明下想法的正确与否:

    //定义父类型,并在类型内部定义了一个实例属性superProperty:
    function SuperType() {
        this.superProperty = "super property";
    }

    //定义原型方法
    SuperType.prototype.getSuperValue = function () {
        return this.superProperty;
    };

    //定义子类型,并在子类型内部定义了实例属性
    function SubType() {
        this.subProperty = "sub property";
    }

    //继承
    //SubType.prototype = new SuperType();
    SubType.prototype = SuperType.prototype

    //定义子类型的原型方法
    SubType.prototype.getSubValue = function () {
        return this.subProperty;
    };

    var instance = new SubType();
    document.write(instance.superProperty + "<br/>"); //super property
    document.write(instance.subProperty + "<br/>"); //sub property
    document.write(instance.getSuperValue() + "<br/>"); //super property
    document.write(instance.getSubValue() + "<br/>"); //sub property
    //以上结果证明,SubType.prototype = new SuperType()会继承父类的所有可见成员,不管是实例成员还是原型成员。
    document.write(instance.constructor + "<br/>");
    //但要注意的是,SubType.prototype = new SuperType()实际上是重写了SubType的原型,所以SubType.prototype原型对象的constructor属性也变为了SuperType,
    //即:instance.constructor==SuperType
    //因此,继承后判断对象类型时要特别注意。

    //如果采用SubType.prototype = SuperType.prototype继承方式,会是什么结果呢?
    document.write(instance.superProperty + "<br/>"); //undefined
    document.write(instance.subProperty + "<br/>"); //sub property
    document.write(instance.getSuperValue() + "<br/>"); //undefined
    document.write(instance.getSubValue() + "<br/>"); //sub property
    //结论:采用这种纯原型继承的方式只继承了父类原型上的成员,如上所示,父类定义的实例属性superProperty值为undefined,
    //说明实例instance中不存在这个属性,但是包含父类的原型方法getSuperValue()。
    //与上面相同的是,instance.constructor还是SuperType,因为这样也相当于是重写了SubType.prototype原型对象。

  • 相关阅读:
    asp.net获取服务端和客户端信息
    ASP.NET 中JSON 的序列化和反序列化
    Asp.net TextBox常规输入验证
    ADO.NET中的五个主要对象
    .Net一般处理程序来实现用户名的验证
    .net获取当前网址url(各种参数值)
    hdu-1941 Find the Shortest Common Superstring
    字典树的动态与静态模板
    模板 Dijkstra+链式前向星+堆优化(非原创)
    基础深搜小结
  • 原文地址:https://www.cnblogs.com/zhaow/p/9754426.html
Copyright © 2011-2022 走看看