search

Home  >  Q&A  >  body text

javascript - 红皮书中原型链的问题

红皮书p165 页说:给原型添加方法的代码一定要放在替换原型的语句之后,但我下面代码改成2,3,1的顺序,添加方法的代码还是有效?为什么?

function SuperType() {
        this.property = 'super';
    }

    SuperType.prototype.getSuperValue = function () {
        return this.property;
    };

    function SubType() {
        this.subproperty = 'sub';
    }

    //2
    SubType.prototype.getSubValue = function () {
        return this.subproperty;
    };
    //3
    SuperType.prototype.getSuperValue = function () {
        return 'change';
    };
    //1
    SubType.prototype = new SuperType();

    var instance = new SubType();
    alert(instance.getSuperValue());//change
阿神阿神2902 days ago299

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-04-10 17:26:47

    Subtype实例的getSubValue方法会无效

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 17:26:47

    SuperType的getSuperValue方法在后面被覆盖了。

    SubType的prototype后面被SuperType覆盖了,所以可以得到getSuperValue的输出为“change”.

    同时SubType的getSubValue方法不在SubType的原型链上了。

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-10 17:26:47

    LZ你再自己理一下;
    在执行//1后SubType.prototype看上去应该是这个样子:

    instance看上去应该是这个样子:

    所以啊,LZ,你应该验证的是instance.getSubValue方法啊--!

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 17:26:47

    getSuperValue() 本来就应该有效啊,相当于父类原型上的方法,你应该验证的是 实例对象指向的原型上的方法 ,即 .getSubValue

    reply
    0
  • Cancelreply