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
2010-07-29 07:36:56
And totally unrelated to the post: This was my 500th answer :P
Tomas Lycken
2010-07-29 07:37:18
@Tomas - What is the difference of jsonObject.functionName = ... and jsonObject.prototype.functionName = .... ?
uzay95
2010-07-29 07:49:32
@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
2010-07-29 09:02:41