假设我有一个来自类的对象,其中包含如下所示的方法和属性:
function Fruit (type, color) {
this.type = type;
this.color = color;
this.getInfo = function() {
return this.color + ' ' + this.type;
};
this.loadJSON = function() {
//TODO
};
}
var red_apple = new Fruit ('apple', 'red');
我想从 JSON 加载新数据,例如:
red_apple.loadJSON( '{"new_apple": {"color": "green", "type": "apple"}}' );
我将如何实现this.loadJSON
?有标准功能吗?
最佳答案
尝试 jQuery 扩展功能
function Fruit (type, color) {
this.type = type;
this.color = color;
this.getInfo = function() {
return this.color + ' ' + this.type;
};
this.loadJSON = function(json) {
//TODO
var jsonFruit = JSON.parse(json);
$.extend(this, jsonFruit.new_apple);
};
}
var red_apple = new Fruit ('apple', 'red');
console.log(red_apple.getInfo()); // Prints "red apple"
red_apple.loadJSON( '{"new_apple": {"color": "green", "type": "apple"}}' );
console.log(red_apple.getInfo()); // Prints "green apple"
关于javascript - 仅将 JSON 中的属性加载到现有 javascript 对象中,而不破坏方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350632/