我正在尝试执行以下操作来满足代码生成器(具体来说是 Sencha Cmd)的要求。
这就是我需要做的本质。关键因素是函数体必须以返回对象文字结束。由于构建器的限制,我无法返回变量。那么,如果参数“includeB”为 true,如何在下面的伪代码处添加属性“b”,但如果参数“includeB”为 false,则根本不添加属性。即 b==undefined 或 b==null 是不允许的。
也许这是不可能的。
function create(includeB) {
// Can have code here but the final thing MUST be a return of the literal.
// ...
return {
a : 1
// pseudo code:
// if (includeB==true) then create a property called b
// and assign a value of 2 to it.
// Must be done right here within this object literal
}
}
var obj = create(false);
// obj must have property 'a' ONLY
var obj = create(true);
// obj must have properties 'a' and 'b'
感谢您的阅读和考虑,
Murray
如果你可以使用 ES6,请使用传播特性.
function create(includeB) {
return {
a : 1,
...(includeB ? { b: 2 } : {}),
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)