tags:

views:

51

answers:

1

Hi all,

Is it possible to create your own custom, I believe the term is 'method'? For example, something like this:

var str = "test"
str.replaceSpecial();

where replaceSpecial() will automatically replace say, the letter e with something else.

The reason I'm interested in doing this is because what I want to do is grab strings and then run a large number of replace actions, so I'm hoping that when I call on replaceSpecial() it will run a function.

Thanks

+7  A: 

You can add your methods to String.prototype which will become available to all strings. That is how trim() is implemented in most libraries for example.

String.prototype.replaceSpecial = function() {
    return this.replace(/l/g, 'L');
};

"hello".replaceSpecial(); // heLLo

However, note that it is generally a bad practice to define very specific functionality on the native prototypes. The above is a good example of exactly the same problem. For such specific cases, consider using a custom function or wrapper to do the job.

function replaceSpecial(str) {
    return str.replace(/l/g, 'L');
}

replaceSpecial("hello"); // heLLo

or under a custom namespace, for example.

var StringUtils = {
    replaceSpecial: function(str) { .. },
    ..
};

StringUtils.replaceSpecial("hello"); // heLLo
Anurag
Thank you for your help. :)
Pete
You're most welcome :)
Anurag
+1. It might be worth mentioning that it's never ok to augment `Object.prototype` or `Array.prototype`. There have been a few cases where modifying other built-in constructor prototypes have been sketchy too... for example the dynarch calendar script modifies `Date.prototype` which ends up breaking some other common script, I can't remember which one at the moment.
no
@no - I don't agree with that statement and since this issue keeps coming up, I wrote a lengthy [blog post](http://vombat.tumblr.com/post/686555405/enumerating-arrays-and-objects-in-javascript) about it.
Anurag
@Anurag Yay! I'm so sick of hearing "Don't do anything *ever* in Javascript because some code written in 1998 sucks".
MooGoo
I agree that it IS okay to augment Object/Array.prototype. Just don't use or write stupid code, such as using a for-in loop to go through an array (really slow) or using a for-in loop without using `obj.hasOwnProperty (prop)`. Just because people have written bad libraries is no reason not to write code that SHOULD be okay. Keep the habit. Ditch the library.
trinithis
@MooGoo @trinithis - glad to know there are others that are sick of conventions :)
Anurag
@Anurag: I read the blog post, but I don't see where you address the normal concerns about modifying Object and Array prototypes, ie conflicts with other libraries, iterating objects and arrays, fowling up feature detection, etc. @trinithis if it's for a library, "just don't use stupid code" is not an option. Your users will inevitably do something "stupid" that normally works for them, exactly like iterating an array with for-in, or not using hasOwnProperty.
no
@no - Sorry, it wasn't the whole post, but one para towards the end and some code samples :). Also, posted my opinion on the issue in this [answer](http://stackoverflow.com/questions/2913675/extending-object-in-javasript/2919117#2919117). If conflicts are a problem then seal the object or the property from further changes. Any further conflict or race conditions will be immediately detected. This, of course, requires support for ECMAScript 5 features, but they're almost upon us.
Anurag
@Anurag: even with the ability to seal the property, you're still blocking anything else that wants to use it from using it. Of course they shouldn't be doing thet anyway by my logic, but by yours it should be fine. So if you seal it first, their scripts will break, and if they seal it first, your scripts will break. It's better if everything exposes as little as possible into the global scope, like a single point of entry, then there are no conflicts.
no
@no - the point was that code breaking is not bad, as long as an error is thrown. Silent failures are the worst kind of failures. And namespacing is not the result to all coding problems. At the end of the day, it's dealing with the DOM which itself is a shared resource. There can potentially be conflicts between two very well namespaced jQuery plugins for example because they are operating on a shared element. Script and plugin mashups are good upto a certain level of application size beyond which it becomes important to realize exactly what is going on in the app.
Anurag