If one has an existing object obj
:
const obj = {
i: 0,
foo(){
console.log(this.i)
this.i +=1
}
}
obj.foo() // => 0
Is it possible to merge a function into it:
// the following function code should be added to `obj`
function obj(){
this.foo()
}
// after the merge the following should both work:
obj.foo() // => 1
obj() // => 2
3
Answers
You can merge function to object using
Object.assign
. I changedobj()
tobaz()
to make it more clear.However when you call
baz()
, it will throw error because it doesn’t understand the contextthis
in baz(). So you need to callbaz()
withobj
as the contextI am not sure how the
obj
function is merged into theobj
object if you want to call it standalone. However, you could use a bound function instead.Besides: You cannot have a constant
obj
and a functionobj
that share the same name. I therefor changed the function name tofn
:there are multiple ways to add property to an object like :