this 指向
this 指向函数执行时的上下文。
全局上下文
函数上下文
普通函数
1 2 3 4 5
| function func() { console.log(this) }
func()
|
对象方法
1 2 3 4 5 6 7
| const obj = { func() { console.log(this) } }
obj.func()
|
构造函数
1 2 3 4 5 6
| function Person(name) { this.name = name }
const person = new Person('Alice') console.log(person.name)
|
箭头函数
箭头函数没有自己的 this,继承外层。
1 2 3 4 5
| const obj = { func: () => console.log(this) }
obj.func()
|
改变 this
call()
1
| func.call(obj, arg1, arg2)
|
apply()
1
| func.apply(obj, [arg1, arg2])
|
bind()
1 2
| const boundFunc = func.bind(obj) boundFunc()
|
常见坑
总结
this 的指向是 JavaScript 中经常让人迷惑的概念,掌握 call、apply、bind、箭头函数以及严格模式规则,可以在编写回调、事件处理和类方法时避免错误。建议在开发时保持一致性,明确组件/模块之间的边界。
箭头函数与 this
箭头函数没有自己的 this,它绑定创建时的上下文:
1 2 3 4 5
| const obj = { value: 10, getValue: () => this.value }; console.log(obj.getValue());
|
类方法中的 this
在 ES6 类中,方法的 this 通常指向实例,可通过 bind 固定:
1 2 3 4 5 6 7 8 9
| class Timer { constructor() { this.seconds = 0; setInterval(this.tick.bind(this), 1000); } tick() { this.seconds++; } }
|
DOM 事件中的 this
事件处理函数中的 this 默认指向绑定的 DOM 元素:
1 2 3
| element.addEventListener('click', function() { console.log(this); });
|
使用箭头函数则 this 指向外层环境。
坑与避雷
- 在回调中传递方法时忘记绑定
- 与 React/Angular 等框架中的
this 差异
- 在严格模式下
this 为 undefined,非法调用可报错
调试技巧
- 在 Chrome 控制台使用
this 快捷键
- 通过
console.log(this) 检查当前指向
- 使用 IDE 的“跳转到定义”功能查看上下文
总览
理解 this 后,编写面向对象的 JavaScript、处理事件和使用框架时会更加自如。大量练习和阅读他人代码有助于巩固概念。
this 灵活但复杂。多练习,理解不同场景下的指向。