Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 244
MGOwen Avatar asked Jul 02 '09 04:07

MGOwen


2 Answers

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
like image 173
John Kugelman Avatar answered Oct 25 '22 05:10

John Kugelman


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.

like image 35
Greg Hewgill Avatar answered Oct 25 '22 05:10

Greg Hewgill