开发者

Is there any way to add method to JSON object?

Is there开发者_如何转开发 any way to add method to JSON object?


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


It all depends on how you're using it.

By using Tomas's function your actually storing Sum for EACH object you attach it too.

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

Bad one:

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

Good one:

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

In my tests the good one took ~3mb extra, the bad one took ~20mb extra. This happens because you're storing only 100000 references to a function, instead of 100000 anonymous functions.

The approach you are referring to (the prototype based one) in your comment could be coded up as this:

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({})

Memory-wise is roughly the same as the Good one I wrote before but has the advantage of not polluting our object with the function name (test, in the example).

The disadvantages are mainly the length, the need to copy our data and the "hack" used to copy (which may be valid in certain designs and totally awful in other ones).


Yes, it's just like any other object:

From the Chrome console:

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


It is simple ....

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

Now Method Implimentation

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

Now You can Use FillCbo.Category() as a method anywhere in the Page

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜