javascript - Should data functions be properties of a data array? -
i have dataset , functions manipulate data. store data , functions in logical structure readable , easy use without violating practices.
i see 2 options:
1. define data array , add manipulation functions array, possible because array kind of object.
example:
var dataset = [1, 2, 3, 4]; var dataset.add = function (newdata) { if (newdata === baddata) { console.log('bad data!'); return; } dataset.push(newdata); };
pros: cleaner, more readable, easier use
cons: modifying array object, means not behave expected, should not try copy object example, or document fact doing causes lose it's functions.
2. define new object , define data property of object along manipulation functions.
example:
var dataset = { data: [1, 2, 3, 4], add: function (newdata) { if (newdata === baddata) { console.log('bad data!'); return; } data.push(newdata); } };
pros: object works expected, can duplicated easily, , packages data , functions neatly.
cons: data cannot referenced canonical representation of object calling 'dataset'. data manipulation become tedious write in cases, due need call dataset.data instead of calling dataset.
which of these 2 options best , why? examples of these options in use today?
feel free offer better options well.
edit:
option 2a: (use prototype if have more 1 dataset)
option 3: don't attach data functions @ all. instead create separate array data outside of functions object , put data functions own object.
thanks!
in opinion second option better, cause said, modifying native object bad practice.
actually there third option, can create class
, native data structure , expose method on it.
in way, able create multiple instances of same class.
class dataset { constructor(data) { this.data = data; } add(newdata) { if (newdata === baddata) { console.log('bad data!'); return; } data.push(newdata); } }
same implementation es5
var dataset = (function () { function dataset(data) { this.data = data; } dataset.prototype.add = function (newdata) { if (newdata === baddata) { console.log('bad data!'); return; } data.push(newdata); }; return dataset; }());
wiki
Comments
Post a Comment