返回
深入理解 JavaScript this 关键字
前端
2024-02-13 17:15:22
this 的常见使用场景
1. 箭头函数
箭头函数(=>)中没有自己的 this,它会从周围的词法作用域继承 this。
const obj = {
name: 'Tom',
sayHello: () => {
console.log(this.name); // undefined
}
};
obj.sayHello(); // undefined
2. 对象方法
对象方法中的 this 指向调用它的对象。
const obj = {
name: 'Tom',
sayHello: function() {
console.log(this.name); // Tom
}
};
obj.sayHello(); // Tom
3. 事件处理程序
事件处理程序中的 this 指向触发事件的元素。
const btn = document.querySelector('button');
btn.addEventListener('click', function() {
console.log(this); // <button>...</button>
});
4. 构造函数
构造函数中的 this 指向正在创建的新对象。
function Person(name) {
this.name = name;
}
const person = new Person('Tom');
console.log(person.name); // Tom
5. call 和 bind
call 和 bind 方法可以改变函数的 this 指向。
const obj = {
name: 'Tom'
};
function sayHello() {
console.log(this.name);
}
sayHello.call(obj); // Tom
sayHello.bind(obj)(); // Tom
6. 全局 this
全局 this 指向 window 对象。
console.log(this); // window
手动实现 call 和 bind
我们可以手动实现 call 和 bind,以便更好地理解它们的原理。
Function.prototype.myCall = function(obj, ...args) {
obj.fn = this;
obj.fn(...args);
delete obj.fn;
};
Function.prototype.myBind = function(obj, ...args) {
return (...bindArgs) => {
obj.fn = this;
obj.fn(...args, ...bindArgs);
delete obj.fn;
};
};
结语
通过本文的学习,希望你能对 JavaScript 中的 this 有更深入的理解。在实际开发中,灵活运用 this 可以使你的代码更加简洁、优雅。