开发者

Initialize a JavaScript object using JSON

开发者 https://www.devze.com 2023-02-25 08:26 出处:网络
I want to do the following var my_json = { a : \'lemon\', b : 1 } function obj(json){ this.a =开发者_如何学JAVA \'apple\';

I want to do the following

var my_json = {
    a : 'lemon',
    b : 1
}

function obj(json){
    this.a =开发者_如何学JAVA 'apple';
    this.b = 0;
    this.c = 'other default';
}

after assigning

var instance = obj(my_json)

I want to get

instance.a == 'lemon'


for(var key in json) {
    if(json.hasOwnProperty(key)) {
        this[key] = json[key];
    }
}

The if block is optional if you know for sure that nothing is every going to extend Object.prototype (which is a bad thing anyway).


If you want defaults how about;

function obj(json){
  var defaults = {
    a: 'apple',
    b: 0,
    c: 'other default'
  }

  for (var k in json)
    if (json.hasOwnProperty(k))
      defaults[k] = json[k];

  return defaults
}
0

精彩评论

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