如何在JavaScript中对两个对象的属性进行求和

3

我正在尝试做一些我不记得/找不到在javascript中是否可能的事情。

我有一个对象构造函数"Point",我想知道是否可以像下面这样对两个不同的对象进行求和。

function Point(x, y) {
    this.x = x;
    this.y = y;
}

a = new Point(1,2);
b = new Point(2,3);
c = a+b;


console.log('a: ', a)
console.log('b: ', b)
console.log('c: ', c)

a = Point {x: 1, y: 2}
b = Point {x: 2, y: 3}
Expected result: c = Point {x: 3, y: 5}

2
你可以创建一个自定义方法 a.add(b),在其中使用适当的对象类型进行求和。 - deceze
这么快, 谢谢 :)所以, 像这样对吧?Point.prototype.add = function(point2){ return new Point(this.x + point2.x, this.y + point2.y) } a.add(b); - Jóni
1
是的,但我建議你使用Point.add(obj1, obj2)而不是obj1.add(obj2)。第一種方式看起來更加整潔。 - Raghav Garg
好的,明白了。谢谢。 - Jóni
@Raghav 那不算真正的面向对象编程。使用a.add(...),您可以使用其他几何形状子类化a,对于这些形状添加点也有意义。使用Point.add(...),您将硬编码行为仅适用于点。 - deceze
5个回答

4
function sumOfObjects(Obj1, Obj2){
    var finalObj = {};
    this.keys(Obj1).forEach(value =>{
        if (Obj2.hasOwnProperty(value)) {
            finalObj[value] = Obj1[value] + Obj2[value]
        }  
    });
    return finalObj;
 }

2
你可以为此创建一个函数。这个函数应该接受两个点作为参数就足够了,然后在实现中创建一个新的点,其中包含每个属性的总和。
function addPoint(pointA, pointB) {
 const newX = pointA.x + pointB.x;
 const newY = pointA.y + pointB.y;
 return new Point(newX, newY);
}

这是最基本的代码,但例如允许多个参数然后生成它们的总和需要另一种不同的方法。


好的,谢谢你的回答。但是直接使用+运算符是可能的吗?有没有办法在自定义对象上实现它? - Jóni

1
你可以像下面的代码一样做。我们在Point函数上添加了一个静态方法,它将添加两个对象并返回新对象。

function Point(x, y) {
    this.x = x;
    this.y = y;
}

Point.add = function(a, b) {
    const x = a.x + b.x;
    const y = a.y + b.y;
    return new Point(x, y)
}

a = new Point(1,2);
b = new Point(2,3);
c = Point.add(a, b)


console.log('a: ', a)
console.log('b: ', b)
console.log('c: ', c)


好的,谢谢你的回答。但是直接使用+运算符是可能的吗?有没有办法在自定义对象上实现它? - Jóni
没有直接的方法来实现 object + anotherObject。也许 Js Proxy 可以帮助你,但我真的不确定。 - Raghav Garg

1

所以,事实证明这是可能的。只是不建议这样做。

我在一篇旧帖子中找到了解决方案:JavaScript中的虚拟运算符重载文章和git JavaScript代码的虚拟运算符重载

credit to Axel Rauschmayer, the author

function Point(x, y) {
  if (arguments.length === 0) {
    x = 0;
    y = 0;
  } else if (arguments.length !== 2) {
    throw new Error("Need either 0 or 2 arguments");
  }
  this.x = x;
  this.y = y;
}

//-------------- Operator overloading
Point.operands = [];

Point.prototype.valueOf = function() {
  Point.operands.push(this);
  // Lowest natural number x where the following are all different:
  // x + x, x - x, x * x, x / x
  return 3;
}
Object.defineProperty(Point.prototype, "_", {
  set: function(value) {
    var ops = Point.operands;
    var operator;
    if (ops.length >= 2 && (value === 3 * ops.length)) {
      operator = this.setAdd;
    } else {
      throw new Error("Unsupported operation (code " + value + ")");
    }
    Point.operands = []; // reset
    return operator.apply(this, ops);
  },
  get: function() {
    return this.toString();
  }
});

//-------------- Operator implementations
Point.prototype.setAdd = function(first) {
  this.x = first.x;
  this.y = first.y;
  [].slice.call(arguments, 1).forEach(function(op) {
    this.x += op.x;
    this.y += op.y;
  }, this);
  return this;
}

//-------------- Various helpers
Point.prototype.toString = function() {
  return "Point(" + this.x + ", " + this.y + ")";
}
Point.prototype.equals = function(other) {
  return this.x === other.x && this.y === other.y;
}

//-------------- Testing it
var p = new Point();
var a = new Point(1, 2);
var b = new Point(4, 3);

p._ = a + b;
console.log(p); // Point {x: 5, y: 5}


0

你不能简单地使用+运算符。在JavaScript中,如果一个对象在AdditiveExpression中,它将被转换为原始值(字符串或数字)。

因此,在JavaScript中没有一种干净的方法来对两个对象的属性求和,你可能需要创建一个额外的函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接