当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Any way to create a Object that extends Array?

问题描述:

I have created a lexer in javascript, and where im now using an array to describe a range of items, i now see the use of having my own Range object so i can properly distinguish an "array" and a "range array" in such a way that it reads nicely.

So is there any way i can create a hugely cross browser compatible sublcass of the Array object?

Or would a better/simpler approach just using array as is, and for "range arrays" i just tag the array with a property of my own choosing?

something like:

var myRange = [1,2,3];

myrange.isRangeObj = true;

//i would then use if(myRange.isRangeObj) to do specific range operations.

//However i still think myRange instanceof Range reads better

网友答案:

You can use this:

Array.prototype.isRangeObj = false;

So all the arrays created by you will have the property isRangeObj

网友答案:

Use composition in javascript to create an Object that extends Array:

function Range(arr) {
  this.arr = arr;
}

var myRange = new Range([1, 2, 3]);

if (myRange instanceof Range) {
    doSomethingWithRange(myRange.arr);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: