The first way:
const logger = () => ({
log(msg) {
console.log(msg)
}
})
class Component {
constructor() {
Object.assign(this, logger())
}
}
The second way:
const logger = {
log(msg) {
console.log(msg)
}
}
class Component {
constructor() {
Object.assign(this, logger)
}
}
Now, what is the difference between the two?
const obj = new Component()
obj.log('what is the difference?')
I see the first piece of pattern multiple times in people's code. Is there a name for this IFFE-ish pattern? In what scenario do we use this pattern?
I simplified it to the second piece of code, still works. It seems to work the same?
The first example creates a new object (and a new log function) every time an instance of Component is created.
The second example reuses the same one each time (so any changes to log would be shared).
In short, they will yield the same result on your example. That's because Object.assign itself will always return a new object, which is composed by the objects you passed as arguments. In both cases you are calling it with the same arguments, being the case you are invoking a factory function to create the object, or if you are passing a simple object literal, so any mutation on the instance objects will not affect the original object.
Object.assign documentation
The difference being that on the second case, the log function is shared across all instances, that's because running a factory function will create a new object every time, therefore a new function, but having it inside of an object and referencing the object will return the same function.
The first approach would be useful if you had to pass in arguments to create a dynamic object based on them. The danger of this approach is that because you are returning a new function every time, you could potentially be creating some performance issues depending how many instances you intend to create. You could solve this problem by having a third option
const log = (msg) => console.log(msg);
const logger = () => ({ log });
class Component {
constructor() {
Object.assign(this, logger())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With