const obj1 = { a: 1 };
const obj2 = { a: 2 };
function test() {
console.log(this.a);
}
test(); // undefined
test.bind(obj1)(); // 1
test.bind(obj2)(); // 2
test.bind(obj1).bind(obj2)(); // 1
// 只是模拟效果,不是模拟实现bind
// test.bind(obj1) => tempFun1
function tempFun1() {
return test.call(obj1);
}
tempFun1(); // 1
// test.bind(obj1).bind(obj2) => tempFun2
function tempFun2() {
return tempFun1.call(obj2);
}
tempFun2(); // 1
简而言之,func.bind(obj)
返回的新函数 boundFunc
中,func
内部的 this
指向并不依赖于 boundFunc
的 this
,而是直接指向 obj
。
事实上,后续的重复 bind
也只是在改变 boundFunc
的 this
指向,而不是在改变 func
的 this
指向。