Reputation: 402
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)
Upvotes: 2
Views: 295
Reputation: 816322
Destructuring is the same as assigning a property to a local variable. I.e. in your case it would be the same as
var foo = functions.foo;
var bar = functions.bar;
Functions are not bound to their "parent" object. What this
refers to depends on how a function is called. foo()
and functions.foo()
are two different ways of calling a function, hence this
has a different value in each case.
This nothing new to ES6 or destructuring, JavaScript has always worked like that.
See How does the "this" keyword work? .
Upvotes: 2