只将JSON中的属性加载到现有的javascript对象中,而不破坏方法
Loading only properties from JSON into existing javascript object without destroying methods
假设我有一个来自类的对象,该类包含如下方法和属性:
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"
试试这个:
this.loadJSON = function(json) {
//TODO
var jsonFruit = JSON.parse(json);
this.color = jsonFruit.new_apple.color;
this.type = jsonFruit.new_apple.type;
};
相关文章:
- 序列化数据属性中对象的最可靠方法
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 如何从对象的原型方法访问JavaScript对象属性
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- 设置嵌套对象属性的更好方法
- JQuery示例不起作用-“;对象没有't支持属性或方法'按钮'&”;
- 对象不支持属性或方法“自动完成”
- call()和apply()实际上是用来欺骗方法处理类似数组的对象的
- 对象文字方法上的Javascript绑定不起作用
- Meteor应用程序无法运行-对象#<编译器>没有方法'主机'
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- Underscore.js某些对象的所有方法的总和
- 对象#<XMLHttpRequest>没有方法'完成'
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- 丢失对象“;这个“;方法中的上下文
- 如何在ajax中调用javascript对象的方法
- 为什么页面方法对象未定义
- 如何使用在另一个文件中定义的JavaScript方法/对象
- 如何告诉JsHint忽略“未解析的函数或方法”?对象上的警告
- 使用jinja/javascript动态创建方法/对象