Is it okay to attach methods to singleton arrays in javascript? -


is there reason why attaching methods individual instance of array might inadvisable?

everyone on team seems agree fine:

function communicate() {   console.log(this.sound); }  var maru     = {name: 'maru',     sound: 'prrrrrr'}; var garfield = {name: 'garfield', sound: 'anyone lasagna?'}; maru.talk = garfield.talk = communicate; 

there's option of making formal constructor, if need 1 cat, it's nice don't have bother.

this bit more controversial on team:

function socialize() {   this.foreach(function(creature) {     creature.talk();   }); }  var cats = [garfield, maru]; cats.meowfest = socialize;  cats.meowfest(); //=> prrrrrr //=> lasagna? 

other developers on team insist must subclass array rather adding methods on-the-fly. me, seems same fundamental principle in first example. there's option of making formal constructor, if need 1 cats array, it's nice don't have bother. wrong?

so far, i've heard 2 arguments against it:

  1. it's monkey patching , monkey patching dangerous.

this isn't monkey patching. agree monkey patching bad practice, in case, you're not affecting prototype @ all. modified instance, not prototype. here's proof:

var arr1 = []; arr1.foo = function() {return 'bar'}; arr1.foo(); // 'bar'  var arr2 = []; arr2.foo(); // undefined not function 

adding method arr1 safe , did not affect arr2 @ all.

  1. it breaks for-in.

you don't use for-in on arrays anyway, for-in objects , returns keys. arrays, return integers 0 length. instead, use foreach, works fine.

var letters = ['a', 'b', 'c']; letters.foo = function() {return 'bar'}; (key in letters) {   console.log(key); } //=> '0' //=> '1' //=> '2' //=> 'foo'  letters.foreach(function(letter) {   console.log(letter); }); //=> 'a' //=> 'b' //=> 'c' 

the output of for-in wasn't particularly useful before added method. logs method name though, me seems intuitive behavior. moreover, output foreach unaffected, wanted.

so how community feel adding methods array on-the-fly? pro or anti?

yes, it's okay. arrays objects, can add arbitrary properties them.

it's true may break code iterates array for...in loop. avoid that, can define property non-enumerable:

object.defineproperty(cats, 'meowfest', {   configurable: true,   writable: true,   value: socialize }); 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -