📌 一、this
的 5 大绑定规则
1. 默认绑定(函数直接调用)
javascript
function show() {
console.log(this); // 浏览器环境:window(严格模式:undefined)
}
show(); // 直接调用
2. 隐式绑定(方法调用)
javascript
const obj = {
name: "obj",
show: function() {
console.log(this.name); // this → obj
}
}
obj.show(); // "obj"
3. 显式绑定(call/apply/bind)
javascript
function show() {
console.log(this.name);
}
const ctx = { name: "ctx" };
show.call(ctx); // "ctx"(强制绑定this)
4. new 绑定(构造函数)
javascript
function Person(name) {
this.name = name; // this → 新创建的实例
}
const p = new Person("Tom");
5. 箭头函数(继承外层 this)
javascript
const obj = {
show: () => {
console.log(this); // this → 外层作用域的this(此处是window)
}
}
obj.show();
💡 二、经典面试题解析
题目1:对象方法中的普通函数
javascript
const obj = {
name: "obj",
show: function() {
setTimeout(function() {
console.log(this.name); // 输出空(this指向window)
}, 100)
}
}
obj.show();
原因 :setTimeout
的回调函数是普通函数,this
默认绑定到全局对象。
题目2:对象方法中的箭头函数
javascript
const obj = {
name: "obj",
show: function() {
setTimeout(() => {
console.log(this.name); // "obj"
}, 100)
}
}
obj.show();
原因 :箭头函数继承外层 show
方法的 this
(即 obj
)。
题目3:多层嵌套中的 this
javascript
const obj = {
name: "obj",
outer: function() {
function inner() {
console.log(this.name); // 输出空(this指向window)
}
inner();
}
}
obj.outer();
解决方法 :使用 inner = () => { ... }
或 const that = this
。
题目4:call 无法改变箭头函数
javascript
const arrowFn = () => console.log(this.name);
const obj = { name: "obj" };
arrowFn.call(obj); // 输出空(箭头函数this不可被修改)
结论 :箭头函数的 this
在定义时就固化,无法通过 call/apply/bind
改变。
题目5:构造函数中的箭头函数
javascript
function Person() {
this.name = "Tom";
this.say = () => {
console.log(this.name); // "Tom"
}
}
const p = new Person();
const say = p.say;
say(); // "Tom"(箭头函数绑定到实例对象)
关键:箭头函数在构造函数中会永久绑定到实例对象。
🔑 三、this 判断口诀
- 普通函数调用 :看是否用
new
→ 是则绑定新对象,否则默认绑定全局对象(严格模式为undefined
) - 方法调用 :绑定到调用它的对象(
obj.method()
→this=obj
) - 显式绑定 :
call/apply/bind
指定的对象优先 - 箭头函数 :向上找最近一层非箭头函数的
this
- 事件回调 :DOM 事件中
this
是触发事件的元素(除非用箭头函数)
⚠️ 四、常见陷阱
- 回调函数丢失 this :
array.map(function(){...})
中的普通函数 - 间接引用 :
const fn = obj.method; fn()
→this
丢失 - 闭包中的 this:嵌套函数默认绑定全局对象
- 严格模式差异 :函数直接调用时
this=undefined
回答: 我了解到的this指向主要包括以下几个部分: 首先是普通函数
的this指向,如果在调用这个函数时没用new,this指向全局对象window,严格模式下为undefined。如果在调用这个函数的时候用new,this的指向为这个新的对象。
然后是对象中方法
里面的this绑定到调用它的对象
然后是显示绑定
比如说函数在执行的时候使用了call,apply,bind函数,this就会指向对应函数里面的对象
然后是箭头函数
里面的this,他会继承外层作用域最近的非箭头函数的this