Since functions are given "global context" when not accessed as a property of an object [1], the following has the same quirk:
const foo = ({bar}) => {
bar(); // this === window
}
because it's just syntactic sugar for:
const foo = (x) => {
var bar = x.bar;
bar();
}
which seems slightly counter-intuitive to me since I now have to re-bind or forgo the sugar.
Is there a way to change this behaviour so that the context isn't changed (besides explicitly setting it via .apply/call/bind)? Are there any plans/proposals for standards to be implemented for it?
[1] Javascript lost context when assigned to other variable
Well, you answered your own question. If you are taking an Object as argument, then any function you pass as a property will already be a method, thus loosing context, regardless of what the syntax looks like.
What you can do is call the bound function from inside the argument's method:
const argumentContainingBar = {
bar: () => { originallyBoundFunction() }
}
Now you can foo(argumentContainingBar)
without loosing context.
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