Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a method to original context when assigned to variable

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

like image 881
reoh Avatar asked Oct 18 '22 05:10

reoh


1 Answers

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.

like image 193
Hugo Silva Avatar answered Oct 22 '22 10:10

Hugo Silva