如何将类中的方法添加到JSON对象

时间:2017-11-28 11:17:34

标签: javascript json

我在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)

2 个答案:

答案 0 :(得分:1)

你介意做一些改变吗?让我们将Thing输入参数更改为Object。然后你可以轻松地将已解析的json传递给它。

适合你吗?

function Thing(obj) {
  
  this.a = obj.a;
  this.b = obj.b;
  
  this.sum = function(){ return this.a + this.b; };
  
  this.printSum = function(){ console.log (this.sum()); };
};

y = JSON.parse('{"a": 5, "b": 4}');
t = new Thing(y);
t.printSum();

可以将对象添加为optinal param:

function Thing(a, b, obj = null) {
  if (!obj) {
    this.a = a;
    this.b = b;
  } else {
    this.a = obj.a;
    this.b = obj.b;
  }
  

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

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

y = JSON.parse('{"a": 5, "b": 4}');
t = new Thing(null, null, y);
t.printSum();

tt = new Thing(5, 4);
t.printSum();

答案 1 :(得分:1)

您需要更改sum函数,使其返回this.athis.b之和。

此外,您需要更改变量Object.assign的原型,而不是y,以便方法可用。



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();