1. this 是什么?
this 是 JavaScript 中的一个特殊关键字,它在函数被调用时自动绑定到一个对象上。this 的值取决于函数的调用方式,而不是函数的定义位置。
2. this 指向什么?
this 的指向取决于函数的调用方式:
- 默认绑定:在独立函数调用中,
this指向全局对象(浏览器中是window,Node.js 中是global)。严格模式下为undefined。 - 隐式绑定:作为对象方法调用时,
this指向调用该方法的对象。 - 显式绑定:使用
call(),apply()或bind()方法时,this指向指定的对象。 - new 绑定:使用
new调用构造函数时,this指向新创建的对象。 - DOM 事件处理程序:在事件处理函数中,
this通常指向触发事件的元素。
3. 箭头函数中的 this
箭头函数没有自己的 this 绑定,它会捕获其所在上下文的 this 值作为自己的 this 值。这意味着:
- 箭头函数内部的
this与定义时所在的作用域的this相同 - 无法通过
call(),apply()或bind()改变箭头函数的this - 不适合用作对象方法(如果需要访问对象自身)
- 适合用在需要保持
this不变的场景,如回调函数
5 个关于 this 的面试题
题目 1:基本 this 指向
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};
obj.greet(); // 输出什么?
const greet = obj.greet;
greet(); // 输出什么?
题目 2:箭头函数的 this
const obj = {
name: 'Bob',
greet: () => {
console.log(this.name);
}
};
obj.greet(); // 输出什么?
题目 3:this 与回调函数
const obj = {
name: 'Charlie',
greet: function() {
setTimeout(function() {
console.log(this.name);
}, 100);
}
};
obj.greet(); // 输出什么?
题目 4:bind 方法
const obj1 = {
name: 'David',
greet: function() {
console.log(this.name);
}
};
const obj2 = { name: 'Eve' };
const greet = obj1.greet.bind(obj2);
obj1.greet(); // 输出什么?
greet(); // 输出什么?
题目 5:构造函数中的 this
function Person(name) {
this.name = name;
setTimeout(function() {
console.log(this.name);
}, 100);
}
new Person('Frank'); // 输出什么?
答案
'Alice'和undefined(或全局对象的 name 属性)undefined(箭头函数继承外层作用域的this)undefined(回调函数中的this默认指向全局对象)'David'和'Eve'(bind创建了绑定this的新函数)undefined(构造函数中的回调函数this指向全局对象)