我想从已经绑定的函数中获取this属性的值。
function foo(){
console.log(this.a)
}
const bar = foo.bind({a:1})
bar() // Prints 1
bar.getThis() // should return { a: 1 }
在上面的示例中,如何从变量栏提取绑定对象{ a: 1 }
?
答案 0 :(得分:2)
您可以通过以下方法扩展内置的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())
答案 1 :(得分:1)
您无法得到,[[BoundThis]]
是绑定函数对象的internal property。
但是您可以在控制台中看到它:
使用标准内置Function.prototype.bind方法创建的函数Object的此值的预绑定。仅使用Function.prototype.bind创建的ECMAScript对象具有[[BoundThis]]内部属性。
正如Bergi所指出的那样:“要在程序逻辑中使用它,您将需要编写自己的绑定版本,以将此值作为属性公开”。
尽管如此,如果您可以添加到foo()
函数中,则可以执行以下操作:
function foo() {
console.log(this.a);
return {
getThis: () => this
};
}
const bar = foo.bind({ a: 1 });
console.log(bar().getThis()) // { "a": 1 }
答案 2 :(得分:0)
本质上是要提取绑定对象{ a: 1 }
,您可以返回或登录this
:
function foo() {
console.log(this);
}
const bar = foo.bind({ a: 1 });
bar(); // { a: 1 }
我希望有帮助。