views:

13

answers:

1

Is there any way to add method to JSON object?

A: 

Yes. Javascript functions are first class objects, which means you can attach them to other objects as properties.

var myJson = { one: 1, two: 2 };

myJson.Sum = function() { return this.one + this.two; };

var result = myJson.Sum(); // result == 3
Tomas Lycken
And totally unrelated to the post: This was my 500th answer :P
Tomas Lycken
@Tomas - What is the difference of jsonObject.functionName = ... and jsonObject.prototype.functionName = .... ?
uzay95
@uzay95: I must admit that I wouldn't put all my money on it - I'm no javascript guru - but after a couple of google searches it seems to me that if you use `jsonObject.funcitonName = ...` you put the function on *that instance*, while `jsonObject.prototype.functionName = ` will end up putting the funciton on the prototype of `Object`, which means *all* your objects of type `Object` will have that method.
Tomas Lycken