0

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
4
  • Why do you need to check that at all? You shouldn't have a non-rangy value in the myRange variable. Commented Feb 21, 2013 at 11:06
  • if (typeof myRange=='object') perhaps ? Commented Feb 21, 2013 at 11:06
  • Yes but i don't have any custom logic, i just want to distinguish a range array and a normal array, later there will be other different array types. Mainly i want to be able to use the same functions as present in the Array object, and also be able to distinguish it as an object of type Range Commented Feb 21, 2013 at 11:07
  • 1
    No. Read how ECMAScript 5 still does not allow to subclass an array Commented Feb 21, 2013 at 11:33

2 Answers 2

1

You can use this:

Array.prototype.isRangeObj = false;

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

Sign up to request clarification or add additional context in comments.

2 Comments

do i need to add it to prototype? would it not suffice to add it to a single instance of array? var arr = []; arr.isRangeObj = false. That way i dont mess with the global scope of array.
Well, I don't really need add it to prototype, it's like you said, I can add only to a single instance, but other instances of Array will return undefined for isRangeObj, so depends of the case, if undefined is enough, so it's better add it to a single instance.
1

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);
}

1 Comment

I guess that is one solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.