面试题库 词条目录
前端Wiki/词条/this 指向绑定

this 指向绑定

定义决定函数运行时 this 到底指向谁的规则,是前端面试必考的 JS 基础题

this 的指向在函数被调用时才能确定,而不是定义时确定。默认规则下,普通函数调用 this 指向 window(严格模式下是 undefined);作为对象方法调用时指向调用它的对象;构造函数里的 this 指向新创建的实例;箭头函数本身没有 this,只能沿作用域链向外层借用。

面试答题时按四步走:先说调用位置决定 this,再列举默认绑定、隐式绑定、显式绑定(call/apply/bind)与 new 绑定四条规则,最后补充箭头函数的特殊性。手写题常考 bind 的实现,核心思路是用闭包保存当前 this,返回新函数并在调用时拼接参数。

JavaScript
// this 绑定的四条规则
function show() { console.log(this.name); }
const obj = { name: 'obj', show: show };

show();                          // 默认绑定:浏览器下指向 window
obj.show();                      // 隐式绑定:指向调用者 obj
show.call({ name: 'call' });     // 显式绑定:指向传入对象
const bound = show.bind({ name: 'bind' });
bound();                         // bind 返回新函数,this 被固定

const arrow = { name: 'arrow', fn: () => console.log(this.name) };
arrow.fn();                      // 箭头函数向外层借用 this
⚠ 常见误区
🔗 相关词条this 指向与 call / apply / bind作用域与闭包
← 返回来源章节this 指向与 call / apply / bind