我有几个polyfill,我在我的解决方案中使用。例如,Array.includes
:
if (![].includes) {
Array.prototype.includes = function(searchElement/*, fromIndex*/) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
var currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)
) {
return true;
}
k++;
}
return false;
};
}
但是我想将我的utils.js
迁移到utils.ts
(我从不使用TS,所以我想玩它),我写了以下内容:
interface Array<T> {
includes(searchElement: T, fromIndex?: number): boolean;
}
if (!Array.prototype.hasOwnProperty('includes')) {
class MyArray<T> extends Array<T> {
includes(searchElement: T, fromIndex?: number): boolean {
const obj = Object(this);
const len = parseInt(obj.length) || 0;
if (len === 0) {
return false;
}
const n = fromIndex || 0;
var k: number;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
const currentElement = obj[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)
) {
return true;
}
k++;
}
return false;
}
}
}
IE中的{p> Array.prototype.includes
仍为undefined
。当然,因为TS正在扩展我的自定义类而不是本地Array
:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
if (!Array.prototype.hasOwnProperty('includes')) {
var MyArray = (function (_super) {
__extends(MyArray, _super);
function MyArray() {
_super.apply(this, arguments);
}
MyArray.prototype.includes = function (searchElement, fromIndex) {
var obj = Object(this);
var len = parseInt(obj.length) || 0;
if (len === 0) {
return false;
}
var n = fromIndex || 0;
var k;
if (n >= 0) {
k = n;
}
else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
var currentElement = obj[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
return MyArray;
}(Array));
}
如何扩展Array
本身?
答案 0 :(得分:1)
而不是bazel-bin/inception/download_and_preprocess_imagenet
执行`Array.prototype.includes = / 在此处插入您的函数 /
class MyArray<T> extends Array<T> {
声明为includes
的成员