Is there a way to add a method to a JSON object?

Is there a way to add a method to a JSON object?

+5
source share
4 answers

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
+11
source

It all depends on how you use it.

Using the Tomas function, you actually save the Sum for an EACH object that you attach too.

If you save the function somewhere else before inserting into your object, you will use less memory.

The bad:

var array = [];
for (i=0; i<100000; i++)
   array[i] = { test: function(){ "A pretty long string" }; }

Good:

var array = [],
    long = function(){ "A pretty long string"; };
for (i=0; i<100000; i++)
   array[i] = { test: long }

~ 3mb , ~ 20mb . , 100000 100000 .

, ( ) , :

function wrapper(data){
   for (i in data)
      this[i] = data[i];   // This is a fast hack
   // You will probably want to clone the object, making sure nested objects and array
   // got cloned too. In this way, nested objects and array will only get their 
   // reference copied inside this
}
wrapper.prototype.test = function(){
   "A pretty long string";
}

  var array = [];
    for (i=0; i<100000; i++)
       array[i] = new wrapper({})

, , , , (test, ).

- , "", ( ​​ ).

+1

, :

Chrome:

> JSON.myMethod = function(x) { console.log(x); }
function (x) { console.log(x); }
> JSON.myMethod("hello")
hello
undefined
0

....

var FillCbo =JSON.parse( '{"Category":""}');
FillCbo.Category = CboCategory;

Implimentation

function CboCategory(PCboName)
{
    Alert(PCboName);
}

FillCbo.Category()

FillCbo.Category("How Are Youu...");
0

All Articles