J S*_*olt 2 javascript binding
我有这段代码:
const data = {
x: "Target"
}
let bar = () => {
console.log(this.x)
}
let final = bar.bind(data);
final();
Run Code Online (Sandbox Code Playgroud)
此代码返回undefined.这是相同的代码,但具有非箭头功能:
const data = {
x: "Target"
}
let bar = function(){
console.log(this.x)
}
let final = bar.bind(data);
final();
Run Code Online (Sandbox Code Playgroud)
这段代码有效.我想理解为什么arrow函数保持绑定不起作用.我知道,他们处理这个不同.我知道他们保留了调用它们的原始上下文,在这种情况下不包括x.但它是否也阻止bind()工作?
但它是否也阻止bind()工作?
部分地,因为bind返回一个用特定函数调用原始函数的新函数this - 但是箭头函数不使用this它们被调用,它们完全忽略它.相反,他们关闭了在this他们定义的位置.
bind关于箭头功能不能改变箭头的概念this.它所能做的只是它的第二个功能,预先提供参数:
"use strict";
function run() {
const f = (a, b, c) => {
console.log("this", this);
console.log("a", a);
console.log("b", b);
console.log("c", c);
};
const fbound = f.bind({}, 1, 2, 3);
f();
fbound();
}
run();Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {
max-height: 100% !important;£
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1039 次 |
| 最近记录: |