Skip to content

__extends继承Array时,不符合预期 #286

@rabit2022

Description

@rabit2022

源码:

class B extends Array{
    get width(): number {
        return 20;
    }
    toString(): string {
        return "class B";
    }
}


const b1 = new B();
b1.push("kkkkk")
console.log(b1.toString());
console.log(b1.width);
//class B
//20

转译代码

(function(){
    "use strict";

    var __extends = (this && this.__extends) || (function () {
        var extendStatics = function (d, b) {
            extendStatics = Object.setPrototypeOf ||
                ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
            return extendStatics(d, b);
        };
        return function (d, b) {
            if (typeof b !== "function" && b !== null)
                throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
            extendStatics(d, b);
            function __() { this.constructor = d; }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
        };
    })();
    var B = /** @class */ (function (_super) {
        __extends(B, _super);
        function B() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(B.prototype, "width", {
            get: function () {
                return 20;
            },
            enumerable: false,
            configurable: true
        });
        B.prototype.toString = function () {
            return "class B";
        };
        return B;
    }(Array));

    var b1 = new B();

    b1.push("kkkkk")
    console.log(b1.toString());
    console.log(b1.width);

})();
// kkkkk
// undefined

b1.toString()走了 原生 Array 的 toString,原型链已经乱了。

对照babel的转译代码,得到的解决方案

// babel   _wrapNativeSuper方法
 // }(Array));
    }(_wrapNativeSuper(Array)));

现在,他可以正常的工作了。

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions