普通函数调用时this指向全局对象或undefined;箭头函数不绑定this,继承外层作用域;call/apply立即执行并传参,bind返回绑定this的新函数;类方法需手动绑定this以防丢失。
this 指向全局对象或 undefined
在非严格模式下,直接调用函数(如 foo()),this 指向 window(浏览器)或 global(Node.js);严格模式下则为 undefined。这不是“意外”,而是语言规范明确规定的默认绑定行为。
容易踩的坑是:把对象方法赋值给变量后调用,丢失原始上下文:
const obj = {
name: 'Alice',
say() { console.log(this.name); }
};
const fn = obj.say;
fn(); // undefined(严格模式)或报错(因为 window.name 通常不是预期值)say 写错了,是调用位置决定了 this
this,它继承外层作用域的 this,所以不能靠它“修复”这种丢失onClick={this.handleClick} 报 this is undefined 就源于此call、apply 和 bind 的区别与适用场景三者都用于显式控制 this,但执行时机和参数传入方式不同:
func.call(obj, arg1, arg2):立即执行,参数逐个列出func.apply(obj, [arg1, arg2]):立即执行,参数以数组形式传入const bound = func.bind(obj, arg1):返回新函数,不执行;后续调用时 this 固定为 obj,且预置部分参数典型用例:
function log(prefix, msg) { console.log(`${prefix}: ${this.name} - ${msg}`); }
const user = { name: 'Bob' };
log.call(user, '[INFO]', 'loaded'); // [INFO]: Bob - loaded
log.apply(user, ['[WARN]', 'timeout']); // [WARN]: Bob - timeout
const warnUser = log.bind(user, '[WARN]');
warnUser('failed'); // [WARN]: Bob - failed
bind 常用于事件监听器或回调中固化上下文,但注意:它会创建新函数,频繁调用可能影响性能或导致移除监听器失败(因引用不一致)。
this 是词法绑定,无法被改变箭头函数没有自己的 this,它沿作用域链向上查找,取最近一层普通函数的 this 值。这意味着:ca/
llapply/bind 对它无效,new 也不可用。
常见误用:
const obj = {
name: 'Charlie',
regular() { return this.name; },
arrow: () => this.name // 这里的 this 指向定义时的外层,不是 obj
};
obj.regular(); // 'Charlie'
obj.arrow(); // 可能是 undefined 或全局 name,取决于外层环境this,例如:const self = this; const arrow = () => self.name;
handler = () => {...})之所以能正确访问 this,是因为它在构造函数执行时被初始化,此时 this 已指向实例this 绑定陷阱类中定义的方法默认是普通函数,this 取决于调用方式,不是定义位置。DOM 事件处理器尤其危险:
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
render() {
const btn = document.getElementById('btn');
btn.addEventListener('click', this.increment); // ❌ this 指向 btn 元素
}
}修复方式有三种,各有利弊:
render 中用 bind:btn.addEventListener('click', this.increment.bind(this)) —— 每次渲染都新建函数,不推荐increment = () => { this.count++; } —— 最常用,但会为每个实例创建独立函数btn.addEventListener('click', () => this.increment()) —— 清晰,但每次点击都新建箭头函数真正容易被忽略的是:第三方库(如 Lodash)的 debounce 或 throttle 默认不绑定 this,必须显式传入第三个参数 { leading: true, trailing: true, maxWait: 500 } 并配合 .bind(this) 或用箭头包装,否则 this 依然会丢失。