Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refering to a method without creating an instance first / map a method with jQuery or any javascript map function

I have this:

var Coords = function(x, y){
        this.x = x;
        this.y = y;
    }

Coords.prototype.toArray = function(){
    return [this.x, this.y];
}

Now I have an array of Coords object. I'd like to convert each Coords instance into an array with the toArray method. I could write a loop, but I'd rather use $.map, as it's shorter and more readable. Unfortunately, this:

return $.map(coords_array, Coords.prototype.toArray);

doesn't work at all. It just stops the execution. The problem might be about how to refer to a method independently of any object. Any way of pointing to a method without creating an instance first? Or to use $.map with a method?

Thanks for your insights.

EDIT: well, in fact, it doesn't stop the execution (this came from another problem) but $.map(coords_array, Coords.prototype.toArray); returns [null, null, null, null, null...]. I find this behavior strange.

like image 808
John Smith Optional Avatar asked Sep 05 '26 13:09

John Smith Optional


1 Answers

Try something like:

return $.map(coords_array, function(val, i) { val.toArray(); });

And refer here for more reference on jQuery's map function.

like image 162
Jordan Denison Avatar answered Sep 07 '26 02:09

Jordan Denison



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!