I have an object with two functions, foo
and bar
. bar
calls foo
.
Normally, this works fine when bar
uses this.foo()
. However, when destructuring the object, this
doesn't refer to the object anymore. In the code snippet below, it is undefined. When I run this in chrome, it refers to the window
object.
Expected output
func1()
foo
objectValue
foo
bar
func2()
foo
objectValue
foo
bar
Actual output
func1()
foo
objectValue
foo
bar
func2()
foo
globalValue (or Uncaught TypeError, in the case of the code snippet, which breaks here)
Uncaught TypeError: this.foo is not a function (in the case of chrome, which breaks here)
*note : to reproduce in chrome, change let val = 'globalValue'
to val = 'globalValue'
let val = 'globalValue'
let functions = {
val : 'objectValue',
foo : function(){
console.log('foo')
},
bar : function(){
console.log('this.val: ' + this.val)
this.foo()
console.log('bar')
}
}
class Class {
func1(functions){
console.log('func1()')
functions.foo()
functions.bar()
}
func2({foo, bar}){
console.log('func2()')
foo()
bar()
}
}
let instance = new Class()
instance.func1(functions)
console.log('\n')
instance.func2(functions)