I'm trying to do something I don't remember/find if it is possible in javascript.
I have an object constructor "Point" and I want to know if it possible to, for example, sum two different objects like bellow.
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}
答案 0 :(得分:2)
您可以为此创建一个函数。应该接受两个点的函数就足够了,然后在实现中创建一个包含每个属性之和的新Point。
function addPoint(pointA, pointB) {
const newX = pointA.x + pointB.x;
const newY = pointA.y + pointB.y;
return new Point(newX, newY);
}
这是您可以执行的最基本的代码,但是例如,还有其他方法,例如允许多个参数,然后为所有参数生成总和,也将需要另一种方法。
答案 1 :(得分:2)
function sumOfObjects(Obj1, Obj2){
var finalObj = {};
this.keys(Obj1).forEach(value =>{
if (Obj2.hasOwnProperty(value)) {
finalObj[value] = Obj1[value] + Obj2[value]
}
});
return finalObj;
}
答案 2 :(得分: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)
答案 3 :(得分:1)
因此,事实证明这是可行的。只是不建议这样做。
在对旧帖子Fake operator overloading in JavaScript article和git Fake operator overloading for JavaScript code进行了进一步的挖掘之后,我找到了解决方案
致谢作者Axel Rauschmayer
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}
答案 4 :(得分:0)
您可能不只是使用+
运算符。在javascript中,如果对象位于AdditiveExpression中,则它将转换为原始值(字符串或数字)。
因此,没有一种干净的方法可以对javascript中两个对象的属性求和,您可能需要创建一个附加函数。