通过将功能列表传递给工厂函数来在javascript中编写对象

时间:2017-12-06 13:05:52

标签: javascript ecmascript-6 object-composition

使用此source

中的示例
const barker = (state) => ({
  bark: () => console.log('Woof, I am ' + state.name)
})

const driver = (state) => ({
  drive: () => state.position = state.position + state.speed
})

const murderRobotDog = (name)  => {
  let state = {
    name,
    speed: 100,
    position: 0
  }
  return Object.assign(
        {},
        barker(state),
        driver(state)
    )
}

如何修改此代码,以便能够根据传递给工厂函数的参数分配功能。

例如,我可以有一个像这样的名字数组:

let properties = ["barker", "driver", "killer" etc... ];
murderRobotDog(name, properties);

它对每个函数名称进行Object.assign吗?

我还在学习新的语法,我尝试使用扩展运算符,如下所示:

return Object.assign({}, ...properties(state));

只有意识到这不是任何一种方法。无法弄清楚如何制作一个循环。该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以创建一个字典,其中键形成函数名称。然后你可以循环遍历属性并执行Object.assign:

const barker = (state) => ({
    bark: () => console.log('Woof, I am ' + state.name)
});

const driver = (state) => ({
    drive: () => state.position = state.position + state.speed
});

let types = {
    barker,
    driver
};

const murderRobotDog = (name, properties) => {
    let state = {
        name,
        speed: 100,
        position: 0
    };

    let obj = {};
    for(let prop of properties) {
        Object.assign(obj, types[prop](state));
    }

    return obj;
}

let properties = ["barker", "driver"];
let result = murderRobotDog('Name', properties);
console.log(result);
result.bark()

输出:

node .\index.js
{ bark: [Function: bark], drive: [Function: drive] }
Woof, I am Name