如何从绑定函数中提取 this 属性?

How to extract the this property from a bound function?

我想从一个已经绑定的函数中获取 this 属性 的值。

function foo(){
  console.log(this.a)
}
const bar = foo.bind({a:1})
bar() // Prints 1
bar.getThis() // should return { a: 1 }

在上面的例子中,如何从变量bar中提取绑定对象{ a: 1 }

你无法理解,[[BoundThis]] 是一个 internal property 绑定函数对象。

但是您可以在控制台中看到它:

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.

正如 Bergi 指出的那样,"to use it in your program logic you will need to write your own version of bind that exposes this value as a property".

尽管如此,如果您可以添加到 foo() 函数,那么您可以按照以下方式做一些事情:

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

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

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

本质上是提取绑定对象 { a: 1 } 你可以 return 或记录 this:

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

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

bar(); // { a: 1 }

希望对您有所帮助。

实现此目的的一种方法是扩展内置 bind 方法,如下所示。

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