1

For some reasons I got to bind a function, say like this:

function test() {
  console.log(this);
}

test();               // Window
test = test.bind({});
test();               // Object {  }

No I could add the line

test = test.bind(null);

to bind to another object. But test will still return {} instead of null, it seems to be bound to {} forever.

But is it really? I could of course store the initial definition of test inside a variable initialTest, say, before binding, and to reset simply do

test = initialTest;

But can it be done more easily?


It would in fact do to instead of test = test.bind(context); call

function bindTest(context) {
  test = (function () {
    console.log(this);
  }).bind(context);
}

every time the context of test shall be changed and therefore remove the initial global definition of test (which is the same as calling

bindTest(window);

at the beginning).

But maybe there is a more elegant way to do it...

DonFuchs
  • 133
  • 7
  • [You can only `bind` a function once](https://stackoverflow.com/questions/20925138/bind-more-arguments-of-an-already-bound-function-in-javascript). What are you trying to achieve exactly? – str Sep 03 '19 at 16:26
  • It would do to override `test` by a function with the same body but bound to another object – DonFuchs Sep 03 '19 at 16:30
  • 1
    Then you should do `const test1 = test.bind(something); const test2 = test.bind(somethingElse);`. I.e. do not overwrite `test`. – str Sep 03 '19 at 16:31
  • And I wanna do this without storing the old function before binding – DonFuchs Sep 03 '19 at 16:31
  • But in my context it is necessary to keep the name `test` (rather not elaborate on my rather intricate context) – DonFuchs Sep 03 '19 at 16:33
  • But let's assume the same call `test()` shall always call the same function but with changing context – DonFuchs Sep 03 '19 at 16:34
  • How about naming the initial function differently and only ever assign the bound functions to `test`? – str Sep 03 '19 at 16:35
  • I added something like that to my question, but still I'm not quite satisfied – DonFuchs Sep 03 '19 at 16:52

0 Answers0