简体   繁体   English

在JavaScript中添加两个或多个函数

[英]Addition of two or more functions in javascript

I have a function which gives three objects 我有一个给出三个对象的函数

function myfunc(one, two, three){
    this.one = one;
    this.two = two;
    this.three = three;
}

var a = new myfunc(6,5,7);
var b = new myfunc(10,4,2);
var c = new mufunc(20,1,8);

This gives the three separate objects which are useful. 这给出了三个有用的独立对象。 However, i want to create a forth object which is the sum of a,b and c. 但是,我想创建第四个对象,它是a,b和c的总和。 In effect this would be the same as: 实际上,这与以下内容相同:

var all = new myfunc(36, 10, 17); 

I can do this manually: 我可以手动执行此操作:

aa = a.one + b.one + c.one
bb = a.two + b.two + c.two
cc = a.three + b.three + c.three

var all = new myfunc(aa, bb, cc)

but is there a better way which is less manual. 但是有没有更好的方法,那就是更少的手动操作。

You could put them into an array and sum their properties in a loop of course: 您可以将它们放入数组并在循环中总结它们的属性:

var list = [a, b, c];
function sum(arr, prop) {
    return arr.reduce((acc, x) => acc+x[prop], 0);
}
var all = new myfunc(sum(list, "one"), sum(list, "two"), sum(list, "three"));

Alternatively, mutate an initially empty instance in a loop: 或者,在循环中更改最初为空的实例:

var all = [a, b, c].reduce((obj, x) => {
    obj.one += x.one;
    obj.two += x.two;
    obj.three += x.three;
    return obj;
}, new myfunc(0, 0, 0));

The only way to achieve this is to create a function to handle this for you, if you're going to be running it regularly. 实现此目的的唯一方法是,如果您要定期运行它,则创建一个函数来为您处理此问题。 Just pass in the objects and the function will handle it: 只需传入对象,函数便会处理它:

 function sum_objects( obj1, obj2, obj3 ) { return new myfunc( (obj1.one + obj2.one + obj3.one), (obj1.two + obj2.two + obj3.two), (obj1.three + obj2.three + obj3.three) ); } 

function myfunc(one, two, three){
    this.one = one;
    this.two = two;
    this.three = three;
}

myfunc.prototype.add = function(){
    return this.one + this.two + this.three
}

var all = new myfunc(36, 10, 17);
all.add()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM