javascript - 仅将 JSON 中的属性加载到现有 javascript 对象中,而不破坏方法

标签 javascript json

假设我有一个来自类的对象,其中包含如下所示的方法和属性:

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/

相关文章:

json - 使用Powershell从AWS JSON提取一些字段

javascript - jquery更新嵌套对象的键

json - 有没有直接替换后缀和前缀的方法?

java - 如何使用 JSON 映射 Java 嵌入对象

javascript - 为什么这个正则表达式这么慢?

javascript - 如何从 CasperJS 中的 "then"方法传递数据?

javascript - 一些(JavaScript)事件重新排序有序的 html 选择选项

javascript - 如何在jquery中获取当前的url

javascript - (初学者)如何动态修改一个json文件

json - 吉拉。通过 JSON 导入时如何设置问题创建者?