Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to detect array calls?

I have question about native javascript calling.

i have a class:

x = function(arr) { this.arr = arr; return this; }
x.prototype.toArray = function() {
       return this.arr;
};
x.prototype.test = function() { alert('but i m object too!'); };

when i calling:

var test = new x(['a','b','c']);

alert(test[0]);

alert(test.test());

need to get result 'a' and 'but i m object too!' dialogs.

I want to use this feature as syntax sugar like uses jquery in core when returning DOM Elements after using selector as array. How to implement that?

UPDATE:

Thank for answer, but i need proofs in jquery code blob on github.

like image 728
xercool Avatar asked Sep 01 '26 07:09

xercool


1 Answers

An array is nothing else than an object which treats numeric properties in a special way. You would have to copy every element of the array to the instance, using the index of the element as property name. You should also set the length attribute, to make it a true "array-like" object.

var X = function(arr) {
    for (var i = 0, l = arr.length; i < l; i++) {
        this[i] = arr[i];
    }
    this.length = arr.length;
};

var x = new X(['a', 'b', 'c']);
alert(x[0]);
like image 71
Felix Kling Avatar answered Sep 02 '26 20:09

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!