如何通过bind或箭头函数固定this指向?
参考答案
bind
fn.bind(obj) 返回绑定了 this 的新函数,不执行;可预设参数;多次 bind 只有第一次生效。
const f = obj.say.bind(obj); f();
箭头函数
自身无 this,取定义时外层作用域的 this,绑定后无法被 call/apply/bind 改变,也不能 new。
选用:需要保留外层上下文用箭头函数;需要延迟绑定或传参用 bind。
如何通过bind或箭头函数固定this指向?
fn.bind(obj) 返回绑定了 this 的新函数,不执行;可预设参数;多次 bind 只有第一次生效。
const f = obj.say.bind(obj); f();
自身无 this,取定义时外层作用域的 this,绑定后无法被 call/apply/bind 改变,也不能 new。
选用:需要保留外层上下文用箭头函数;需要延迟绑定或传参用 bind。
本题来自 计算机知识面试题库,共 921 道题。