扩展本机JavaScript数组 [英] Extend native JavaScript array

查看:121
本文介绍了扩展本机JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从JS本机函数继承一个类?

Is there any way to inherit a class from JS native function?

例如,我有一个像这样的JS函数:

For example, I have a JS function like this:

function Xarray()
{
    Array.apply(this, arguments);
    //some stuff for insert, add and remove notification
}
Xarray.prototype = new Array();

我试图将其转换为Typescript但我失败了!!

I tried to convert it to Typescript but i failed!!

export class Xarray implements Array {
}

编译器要求我定义所有 Array 接口属性。我知道如果我需要这个 Xarray.prototype = new Array(); ,我必须在TS中扩展 Array

The compiler asks me to define all Array interface properties. I know if I need this Xarray.prototype = new Array();, I have to extend Array in TS.

如何在TS中扩展JS本机对象?

How to extend the JS native object in TS?

推荐答案

我认为没有办法继承现有的接口,如Array,

I don't think there is a way to inherit existing interfaces like Array,

export class Xarray implements Array {

}

您应该创建一个函数并使用其原型继承它。 Typescript也会接受它类似于javascript。

You should create a function and inherit it with its prototype. Typescript also will accept it which is similar to javascript.

function Xarray(...args: any[]): void; // required in TS 0.9.5
function Xarray()
{
    Array.apply(this, arguments);
   // some stuff for insert, add and remove notification
}
Xarray.prototype = new Array();

更新:这个讨论得很好并为此提供了最佳解决方案在 jqfaq.com

UPDATE: This one is discussed well and provided the best solution for this at jqfaq.com.

//a dummy class it to inherite array.
class XArray {
    constructor() {
        Array.apply(this, arguments);   
        return new Array();
    }
    // we need this, or TS will show an error,
    //XArray["prototype"] = new Array(); will replace with native js arrray function
    pop(): any { return "" };
    push(val): number { return 0; };
    length: number;
}
//Adding Arrray to XArray prototype chain.
XArray["prototype"] = new Array();

//our Class
class YArray extends XArray {
///Some stuff
}

var arr = new YArray();
//we can use the array prop here.
arr.push("one");
arr.push("two");

document.writeln("First Elemet in array : " + arr[0]);
document.writeln("</br>Array Lenght : " + arr.length);

希望,这可能对你有帮助!!!

Hope, this might help you!!!

这篇关于扩展本机JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆