kornfridge
kornfridge

Reputation: 5200

Attaching a function to an array

var primes=[2,3,5,7]
primes.sync = function(){this[0]=23;}

primes // => [2, 3, 5, 7]

primes.sync()

primes // => [23, 3, 5, 7]

This seems to work perfectly in Chrome.

Are there any reasons to not use this syntax/"feature"? Also, can I count on primes to be behave as a normal array (e.g. when passing it to a function that expects an array)?


This is why I want to use it:

Say I have a peopleList in my program. Functions all over the app will use it like an array. Then, suddenly, I do a POST to the server. I then want the array to query the server directly, and update itself. This would allow for some very elegant code in my angular.js app.

Upvotes: 0

Views: 74

Answers (2)

Joon
Joon

Reputation: 9884

What you would want to do is to add a function to Array.prototype, rather than adding it to an array instance. See below.

Array.prototype.sync = function(){this[0]=23;};

This way, all array instances, including those that have been initialized before adding the function, will automatically be able to use the function at once.

var a = [];

a.sync(); // TypeError: Object [object Array] has no method 'sync'

Array.prototype.sync = function(){this[0]=23;};

a.sync();
a // [23]

var b = [1,2,3];
b.sync();

b // [23, 2, 3]

However, only add those functions that are useful/meaningful/reusable to Array.prototype because it is going to be available for all array instances ever created and will be created.

If your function is going to be used by only few instances. You are better of adding them to each instance like you did above.

Upvotes: 0

user2736012
user2736012

Reputation: 3543

The only trouble you'll likely have will be if you (incorrectly) try to use for-in to iterate the Array. As long as you use a for statement or one of the Array iterator methods to constrain the enumeration to numeric indices, there shouldn't be any trouble.

The Array will continue to behave like a typical Array.

Upvotes: 3

Related Questions