标准JS函数使用动态绑定,this
取决于谁在呼叫上运行的方法,因此,如果我们把它用role.test()
,它将绑定this
到role
。
箭头函数将this
绑定到当前上下文中。例如,如果代码在浏览器的控制台中被写入,则this
被绑定到window
对象。这就是所谓的静态词汇结合,这意味着绑定this
它在定义关闭
如果你不会使用箭头功能,this
将指向对象本身时role
叫:
const role = {
test(variable){
this.toLog(variable);
},
toLog(variable) {
console.log(variable);
}
};
role.test(5);
在这种情况下,我们不希望绑定this
到外的上下文,所以我们跳过静态支持动态的结合之一。
但是,如果我们将此方法用作回调,则根据谁在运行方法,动态绑定将更改this
。为了防止这种情况,我们必须使用bind
创建一个明确的静态绑定到role
。
const role = {
test(variable) {
this.toLog(variable);
},
toLog(variable) {
console.log(variable);
}
};
let test = role.test;
try {
test(20); // will throw an error - this.toLog is not a function - because this points to window
} catch (e) {
console.log(e);
}
test = role.test.bind(role);
test(25); // will work because it's staticly binded to role
'role.toLog()'或使用一个类,所以你可以简单地使用'this.toLog()' – Ties
[在这里你不需要他们不要使用箭头功能!](http://stackoverflow.com/q/34361379/1048572)通过方法语法(在对象字面量中),您可以照常调用'this.toLog'。 – Bergi