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

Loading only properties from JSON into existing javascript object without destroying methods

本文关键字:方法 对象 属性 JSON 加载 只将 javascript      更新时间:2023-09-26

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

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;
};