How to extract the this property from a bound function?

Viewed 166

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?

3 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())

You cannot get that, [[BoundThis]] is an internal property of bound function objects.

You can however see it in the console:

enter image description here

The pre-bound this value of a function Object created using the standard built-in Function.prototype.bind method. Only ECMAScript objects created using Function.prototype.bind have a [[BoundThis]] internal property.

As Bergi pointed out, "to use it in your program logic you will need to write your own version of bind that exposes this value as a property".

Nonetheless, if you can add to the foo() function, then you could do something along the lines:

function foo() {
  console.log(this.a);

  return {
    getThis: () => this
  };
}
const bar = foo.bind({ a: 1 });

console.log(bar().getThis()) // { "a": 1 }

essentially to extract the bound object { a: 1 } you can return or log this:

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

const bar = foo.bind({ a: 1 });

bar(); // { a: 1 }

I hope this help.

Related