在工厂函数中使用 spread 而不是 class `extends`

Using spread in factory function instead of class `extends`

我将 class User ... 替换为下面的工厂函数:

const user = (name, age) => {
    return {
        name: name,
        age: age,
    }
}

我也有一个 admin,我通常 extend 使用 ES6 类。我如何使用传播来为 admin 提供 user 的属性?

const admin = (level) => {
    return {
       level: level,
    }
}

使用工厂函数的一般方法是组合之一。这就是取代继承的地方。要将两个不同的对象组合在一起,您只需 spread the object props, like Eric Elliott's functional mixin approach:

const user = (name, age) => ({ name, age })

// The mixin approach
const withAdminLevel = (level, user) => ({ ...user, level })

console.log(withAdminLevel(1, user('John Doe', 30)))

不过,根据这个想法,我们也可以只使用 admin() 内部的 user() 工厂函数,而不是传入用户。这可以简化您的调用,但在某些情况下可能并不理想(例如,当您需要“升级”用户时):

const user = (name, age) => ({ name, age })

// Use "user" factory function inside to simplify calls
const admin = (level, ...args) => ({ ...user(...args), level })

console.log(admin(1, 'John Doe', 30))

最后,我们可以将这两个结合起来:

const user = (name, age) => ({ name, age })

// The mixin approach
const withAdminLevel = (level, user) => ({ ...user, level })

// Use "user" factory function inside to simplify calls
const admin = (level, ...args) => withAdminLevel(level, user(...args))

const existingUser = user('John Doe', 30)

console.log(withAdminLevel(1, existingUser)) // upgrade
console.log(admin(2, 'Jane Doe', 28)) // still simple to do