Emulate super in javascript

后端 未结 11 1126
生来不讨喜
生来不讨喜 2020-12-08 10:18

Basically is there a good elegant mechanism to emulate super with syntax that is as simple as one of the following

  • this.$super.prop()
11条回答
  •  [愿得一人]
    2020-12-08 10:49

    For those who do not understand the recursion problem the OP presents, here is an example:

    function A () {}
    A.prototype.foo = function (n) {
        return n;
    };
    
    function B () {}
    B.prototype = new A();
    B.prototype.constructor = B;
    B.prototype.$super = A.prototype;
    B.prototype.foo = function (n) {
        if (n > 100) return -1;
        return this.$super.foo.call(this, n+1);
    };
    
    function C () {}
    C.prototype = new B();
    C.prototype.constructor = C;
    C.prototype.$super = B.prototype;
    C.prototype.foo = function (n) {
        return this.$super.foo.call(this, n+2);
    };
    
    
    alert(new C().foo(0)); // alerts -1, not 3
    

    The reason: this in Javascript is dynamically bound.

提交回复
热议问题