Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend a javascript object then 'erase' the extensions after use?

Tags:

javascript

Sometimes I want to add behavior to JS string such as

String.prototype.camelize = function () {
    return this.replace (/(?:^|[-])(\w)/g, function (, c) {
        return c ? c.toUpperCase () : '';
    });
};

However it is commonly agreed that modifying primitive type is a terrible idea.

Is there any patterns I can follow to temporarily assign functions to a type and remove after use? Or any thing similar to ruby's 'class << obj' that modify the prototype of one object only?

EDIT: The point of doing this is to be able to use syntax like

name = s.camelize();

or

if (s.hyphenize().length < 8);

So please don't bother with static function approach.

Also, this question is actually more focused on how should one manipulate js objects to do more with less side effect.

like image 312
miushock Avatar asked Oct 19 '22 13:10

miushock


1 Answers

You can do exactly what you are describing- a JavaScript object is just a bundle of properties, some of which are functions. So if you can create:

String.prototype.camelize = function () {
   return this.replace (/(?:^|[-])(\w)/g, function (, c) {
      return c ? c.toUpperCase () : '';
   });
};

Then you can equally call:

String.prototype.camelize = null;

Once you've done that, your ability to camelize strings is eradicated.

Now, I'm sure you have good reasons for wanting to do things this way, but I can't imagine a situation where the thing you are proposing is the right thing to do. To do something like this in a more idiomatic way you could create a type that wraps a string and offers a camelize function or you could just bind that function to instances of your class - you could even drop it from a utility function library into your class. Throwing functions around is one of JavaScript's great powers.

Be aware that your aversion to utility functions is going to force you to take a lot of long-cuts if you are writing JavaScript. You might need to put some of your preconceptions on one side until you have got to grips with the foundations of the language ( what some might term The Good Parts ) and then revisit them when you have a stronger handle on it. It's not that you can't write correct code in JavaScript, but it is not like other languages that you have used and you have to fit your practices and philosophy to the language, rather than trying to force the language into the shape of your preconceptions. Everyone does that at first and JavaScript is so flexible that it very nearly works, but learning to use it in a more idiomatic way reaps big rewards as you go on.

like image 103
glenatron Avatar answered Oct 22 '22 04:10

glenatron