gpt4 book ai didi

javascript - 如何将方法从类添加到 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 14:54:33 24 4
gpt4 key购买 nike

我有一个用 Javascript 定义的类,其中包含一些成员和方法。我还有一个 JSON 对象,它具有与我的类相同的成员变量,但显然不是方法。将 JSON 对象转换为类实例的最简单方法是什么?

下面是一些可以更好地解释我的情况的代码。我试过使用 Object.assign 但没有成功。这可以在一个类轮中完成吗?

function Thing(a, b){
this.a = a;
this.b = b;

this.sum = function(){ return this.a + this.b; };

this.printSum = function(){ console.log (this.sum()); };
};

// test it works
z = new Thing(4,3);
z.printSum(); // shows 7

// attempt with Object.assign
y = JSON.parse('{"a": 5, "b": 4}'); // initialize y from JSON object
console.log(y);
Object.assign(y, new Thing()); // trying to copy methods of Thing into y
console.log(y); // shows both a and b undefined (assign overwrited also a and b)
y.printSum(); // shows NaN

// trying Object.assing the other way around
y = JSON.parse('{"a": 5, "b": 4}');
Object.assign(new Thing(), y); // trying the other way around
console.log(y); // methods from thing are not present now
y.printSum(); // gives error y.printSum is not a function (obvious, as it is not present)

最佳答案

您需要更改 sum 函数以使其返回 this.athis.b 的总和。

此外,您需要更改变量 y 的原型(prototype),而不是 Object.assign,以便它可以使用这些方法。

function Thing(a, b){
this.a = a;
this.b = b;

this.sum = function(){ return this.a + this.b; };

this.printSum = function(){ console.log (this.sum()); };
};

// test it works
z = new Thing(4,3);
z.printSum(); // shows 7

// attempt with Object.assign
y = JSON.parse('{"a": 5, "b": 4}'); // initialize y from JSON object
console.log(y);
y.__proto__ = new Thing(); // trying to copy methods of Thing into y
console.log(y); // shows both a and b undefined (assign overwrited also a and b)
y.printSum();

关于javascript - 如何将方法从类添加到 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47530248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com