Thursday, 15 April 2010

javascript - How to I prevent prototypes to show on array -



javascript - How to I prevent prototypes to show on array -

i'd extend array functionality functions of own. working fine. however, noticed in console functions "appended" array if data.

fiddle: http://jsfiddle.net/bxfcy/1/

and here code because stackoverflow forcing me post (just click fiddle):

a = [1,2,3]; array.prototype.domagic = function(){ var returnvar = this; returnvar.push(42); homecoming returnvar; } console.log(a); (var n in a){ console.log(a[n]); }

my thought other array functions not shown in array (you know, push). there way not show prototyped functions in array well?

one way utilize object.hasownproperty():

for (var n in a){ if (a.hasownproperty(n)) { console.log(a[n]); } }

a improve way use right iteration idiom arrays:

for (var i=0; i<a.length; i++){ console.log(a[i]); }

or utilize object.defineproperty create domagic property not enumerable:

object.defineproperty(array.prototype, 'domagic', { enumerable: false, configurable: false, writable: false, value: function(){ var returnvar = this; returnvar.push(42); homecoming returnvar; } });

javascript arrays prototype

No comments:

Post a Comment