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...