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
}
精彩评论