Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the this property from a bound function? [duplicate]

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?

like image 952
Souradeep Nanda Avatar asked Sep 18 '25 20:09

Souradeep Nanda


1 Answers

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())
like image 167
Rohith K P Avatar answered Sep 21 '25 15:09

Rohith K P