I want to get the value of the this property from a function which is already bound.
function foo(){
console.log(this.a)
}
const bar = foo.bind({a:1})
bar() // Prints 1
bar.getThis() // should return { a: 1 }
In the above example, how do I extract the bound object { a: 1 }
from the variable bar?
One way you can achieve this is by extending the builtin bind
method like below.
Function.prototype.__bind__ = Function.prototype.bind;
Function.prototype.bind = function(object) {
var fn = this.__bind__(object);
fn.getThis = function () {
return object;
}
return fn;
}
function foo(){
return this.a
}
var bar = foo.bind({a:1})
console.log(bar());
console.log(bar.getThis())
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