相关疑难解决方法(0)

子类化Javascript数组.TypeError:Array.prototype.toString不是通用的

是否可以从javascript数组继承和继承?

我想拥有自己的自定义Array对象,它具有Array的所有功能,但包含其他属性.myobj instanceof CustomArray如果实例是我的CustomArray,我将用于执行特定操作.

在尝试子类化并遇到一些问题后,我发现Dean Edwards的这篇文章指出使用Array对象执行此操作无法正常工作.事实证明,Internet Explorer无法正确处理它.但我也发现了其他问题(目前只在Chrome中测试过).

这是一些示例代码:

/** 
 *  Inherit the prototype methods from one constructor into another 
 *  Borrowed from Google Closure Library 
 */
function inherits(childCtor, parentCtor) {
    function tempCtor() {};
    tempCtor.prototype = parentCtor.prototype;
    childCtor.superClass_ = parentCtor.prototype;
    childCtor.prototype = new tempCtor();
    childCtor.prototype.constructor = childCtor;
},

// Custom class that extends Array class
function CustomArray() {
    Array.apply(this, arguments);
}
inherits(CustomArray,Array);

array = new Array(1,2,3);
custom = new CustomArray(1,2,3);
Run Code Online (Sandbox Code Playgroud)

在Chrome的控制台中输入以下内容即可输出以下内容:

> custom
[]
> array
[1, …
Run Code Online (Sandbox Code Playgroud)

javascript inheritance

34
推荐指数
2
解决办法
2万
查看次数

我如何扩展Array类并保留其实现

我想向Array类添加一些函数(我宁愿不要将它们作为类外部的函数使用,因为理想情况.下,在对象后面键入时可以发现它们)。这是我到目前为止的内容:

export class List<T> extends Array<T> {
    constructor(items?: Array<T>) {
        super(...items)
        Object.setPrototypeOf(this, List.prototype);
    }

    get first(): T {
        return this[0]
    }
}
Run Code Online (Sandbox Code Playgroud)

运行良好:

const list = new List([1,2,3]);
console.log(list.first)
Run Code Online (Sandbox Code Playgroud)

但是如果我尝试运行此命令:

const list = new List([1,2,3]);
console.log(list.map(x=>x*2))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

        super(...items)
        ^
TypeError: Found non-callable @@iterator
Run Code Online (Sandbox Code Playgroud)

理想情况下,我将获得一个对象,该对象等效于new List(this.map(x=>x*2))如何在无需重写Array的所有方法的情况下扩展Array类?

class-extensions typescript

1
推荐指数
2
解决办法
407
查看次数