我正在尝试创建一个扩展本机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
答案 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
}
您的编译器设置已损坏,需要修复。