Can I add a public function to objects in JavaScript? How?

MGOwen picture MGOwen · Jul 2, 2009 · Viewed 18k times · Source

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?

Answer

John Kugelman picture John Kugelman · Jul 2, 2009

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