How to override 'this' parameter of a bound function in javascript

Viewed 1786

I have a function that is already bound by using Function.prototype.bind method. Somehow, I want to override the this parameter of the bound function. But it does not work. Check the description in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind , it says that 'this' can not be override. Is there any workaround/ solution to override 'this' of bind function? My test code:

function testF() {console.log(this)}

var test = testF.bind('abc');
test = test.bind('xyz');
test() // print 'abc' instead of 'xyz'. I'm expecting to print 'xyz'
3 Answers

Answer for general development:

//if the function is declared like this
let call=function(){console.log(this);}
// then you can pull the function out of bind through the prototype.
call.bind({hello:'my firend'});
call();// print {hello:'my firend'}
call= Object.getPrototypeOf(new call()).constructor;
call(); print {window}
call=call.bind({bay:'my darling'});
call(); print {bay:'my darling'}

Disadvantage: you need to call the constructor, as a result of which the body of the function is called and thus may have side effects from the call. For example, a call is calculated 1 time and subsequently the variables in the context of the function but outside of it will be changed or deleted. Or throw an error.

If you have access to the native function, then you need to do this:

function call(){
    console.log(this);
}
call=Object.assign(call.bind({hello:'my friend'}),{owner:call});
let otherCall=Object.assign(call.bind({hello:'my friend'}),{owner:call.owner});
otherCall();
Related