简体   繁体   English

ES6是否可以使用花括号定义为两个或多个对象属性分配相同的值?

[英]ES6 Is there any way to assign the same value for two and more object properties using curly braces definition?

I need to assign the same anonymous arrow function to two different properties of the same object, which is defined with curly braces . 我需要将相同的匿名箭头功能分配给同一对象的两个不同属性,这些属性使用花括号定义。 Eg now I have: 例如,现在我有:

let testObject = {a: (a) => a+1, b: (a) => a+1};

And I want something like (pseudo-code): 我想要类似(伪代码)的东西:

let testObject = {a: b: (a) => a+1};

I actually know how to solve that problem (that is not a problem). 我实际上知道如何解决该问题(这不是问题)。 But if there could be some way to assign the same intermediate (neither the variables, nor the primitives) values to two or more object properties like in a pseudo-code above, that would be very useful, isn't it? 但是,如果像上面的伪代码中那样,可以通过某种方式将相同的中间值 (变量或基元)都分配给两个或多个对象属性,那将非常有用,不是吗?

No, not in the way you describe. 不,不是您所描述的方式。


You could assign the function to a variable, but then it's not anonymous anymore: 您可以将函数分配给变量,但随后它不再是匿名的:

const myFunc = a => a + 1;
const testObject = {a: myFunc, b: myFunc};
let testObject = (fn => ({a: fn, b: fn}))(a => a+1);

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

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