先上现有代码:function A(value) { console.log('called A:' + value.message);}function B(value) { console.log('called B:' + value.message);}var f = { 'A': A, 'B': B};var x1 = { message: 'x1'};f.B(x1);//能得到期望值:called B:im the message of x1现在有一个值:var x2 = { value: 'A', message: '100'};有什么办法能在不使用 if 或 switch ,直接用x2中value的值A调用f的方法A?
2 回答
慕少森
TA贡献2019条经验 获得超9个赞
你这种调用写的有点绕,其实只要理解key/idx的机制即可。
可以 f[ x2.value ]( x2 )
而你目前的思路,我的话则整合成功能型:
function f( obj ) {
let fn = {
A() {
console.log( `called A:${ obj.message }` )
},
B() {
console.log( `called B:${ obj.message }` )
},
}
fn[ obj.value ]()
}
var x2 = {
value: 'A',
message: '100'
};
f( x2 ) // called A:100
添加回答
举报
0/150
提交
取消
