views:

511

answers:

2

I'm sure I've worded this question wrong, but I don't know how to explain it well...

I have a vague idea I've read somewhere that I can add methods to objects in JavaScript - by which I mean something like:

function Exclaimify(aString)
{ 
    return aString + "!";
}

var greeting = "Hello";
alert(greeting.Exclaimify()) // this shows "Hello!" in an alert box

Is this possible? If so, how do I do it?

Edit:

Thanks to the accepted answer, I am now able to do stuff like:

// Adds .left(n) substring function to string prototype, do you can do this:
// "ControlNumberOne".left(7)   // this returns "Control"
// n is the number of chars to return
String.prototype.left = function(n) {
    if (n <= 0) {
        return "";
    }
    else if (n > this.length) {
        return this;
    }
    else {
        return this.substring(0, n);
    }
}

And then call it like:

// controlId is something like "MagicalBox_52", so to get just "MagicalBox":
var ControlType = controlId.left(10);

Which really cleans up the syntax of my code, which is using a bunch of string functions.

Yay! Thanks.

+3  A: 

It sounds like you want to use the technique called monkey patching. That article contains a link to Duck Punching JavaScript - Metaprogramming with Prototype which may help you.

Greg Hewgill
Thanks. Your linked articles weren't as concise as the accepted answer, but still spot on.
MGOwen
+10  A: 

Assign to it just like it's a variable. Then you can use this. Easy!

var obj = {foo: "bar"};

obj.someFunc = function()
{
    return this.foo;
}

That works great... except! Er, except, not on strings, which are immune to this tomfoolery. (They are completely immutable.) However, there's another way, which is to modify the object's "class" and add the method there. And by "class" I really mean "prototype". JavaScript doesn't have classes, it has prototypes. The syntax to modify the String prototype looks like this:

var greeting = "Hello";

String.prototype.Exclaimify = function()
{
    return this + "!";
}

alert(greeting.Exclaimify()) // this shows "Hello!" in an alert box
John Kugelman
brilliant - exactly what I was after.
MGOwen