为什么在扩展Array类时,扩展方法不起作用?

时间:2018-01-21 22:27:34

标签: typescript

我正在尝试创建一个扩展本机Array类的类,但我的扩展方法不起作用。

打字稿

export class List extends Array {
  constructor (arr: Array<any> = []) {
    super();
    copy(arr, this);
  }

  public random () {
    return this[random(this.length - 1, 0)];
  }
}

生成代码

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
function random(maximum, minimum) {
    if (minimum === void 0) { minimum = 0; }
    return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
}
exports.random = random;
function copy(src, target) {
    for (var i in src)
        target[i] = src[i];
}
exports.copy = copy;
var List = /** @class */ (function (_super) {
    __extends(List, _super);
    function List() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return List;
}(Array));
exports.List = List;

为什么List#random方法不起作用?例如:

let b = new List([1,2,3]);
b.random; // undefined
List.prototype.random.bind(b)(); // works

1 个答案:

答案 0 :(得分:1)

  

但我的扩展方法不起作用。

您生成的代码:

var List = /** @class */ (function (_super) {
    __extends(List, _super);
    function List() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return List;
}(Array));

与您的TypeScript不匹配,即..我没有看到copy方法被调用

constructor (arr: Array<any> = []) {
    super();
    copy(arr, this); // this is missing in generated code
  }

修复

您的编译器设置已损坏,需要修复。

相关问题