Is it possible to extend a javascript object then 'erase' the extensions after use? -
sometimes want add behavior js string such as
string.prototype.camelize = function () { return this.replace (/(?:^|[-])(\w)/g, function (, c) { return c ? c.touppercase () : ''; }); };
however commonly agreed modifying primitive type terrible idea.
is there patterns can follow temporarily assign functions type , remove after use? or thing similar ruby's 'class << obj' modify prototype of 1 object only?
edit: point of doing able use syntax like
name = s.camelize();
or
if (s.hyphenize().length < 8);
so please don't bother static function approach.
also, question more focused on how should 1 manipulate js objects more less side effect.
you can describing- javascript object bundle of properties, of functions. if can create:
string.prototype.camelize = function () { return this.replace (/(?:^|[-])(\w)/g, function (, c) { return c ? c.touppercase () : ''; }); };
then can equally call:
string.prototype.camelize = null;
once you've done that, ability camelize
strings eradicated.
now, i'm sure have reasons wanting things way, can't imagine situation thing proposing right thing do. in more idiomatic way create type wraps string , offers camelize
function or bind function instances of class - drop utility function library class. throwing functions around 1 of javascript's great powers.
be aware aversion utility functions going force take lot of long-cuts if writing javascript. might need put of preconceptions on 1 side until have got grips foundations of language ( might term the parts ) , revisit them when have stronger handle on it. it's not can't write correct code in javascript, not other languages have used , have fit practices , philosophy language, rather trying force language shape of preconceptions. @ first , javascript flexible very nearly works, learning use in more idiomatic way reaps big rewards go on.
Comments
Post a Comment