第一种方式:
const logger = () => ({
log(msg) {
console.log(msg)
}
})
class Component {
constructor() {
Object.assign(this, logger())
}
}
第二种方式:
const logger = {
log(msg) {
console.log(msg)
}
}
class Component {
constructor() {
Object.assign(this, logger)
}
}
现在,两者之间有什么区别?
const obj = new Component()
obj.log('what is the difference?')
我在人们的代码中多次看到第一个模式。这种类似 IFFE 的模式有名称吗?我们在什么场景下使用这种模式?
我将它简化为第二段代码,仍然有效。好像效果一样?
最佳答案
每次创建 Component
实例时,第一个示例都会创建一个新对象(和一个新的 log
函数)。
第二个示例每次都重复使用相同的一个(因此将共享对 log
的任何更改)。
关于javascript - "const something = () => ({..."箭头函数模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59391856/