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

Composing object in javascript by passing a list of functionality to a factory function

使用此 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));

才意识到这不是任何一个的工作原理。也无法真正弄清楚如何从中循环。应该怎么做?

您可以创建一个字典,其中的键构成函数名称。然后你可以遍历属性并执行 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