JS的this关键字详解
warning:
这篇文章距离上次修改已过439天,其中的内容可能已经有所变动。
this 关键字在 JavaScript 中是一个特殊的标识符,它是函数执行时的一个隐式参数,代表函数执行时的上下文(也就是说,this 指向的是那个对象,该函数是作为那个对象的方法调用的)。
this 的值在函数被调用时确定,不是在函数被定义时确定,这是 JavaScript 中的一个常见陷阱。
- 在普通函数中使用
this:
在普通函数中,this 指向全局对象,在浏览器中通常是 window 对象。
function foo() {
console.log(this); // 输出 window 对象
}
foo();- 在对象方法中使用
this:
在对象方法中,this 指向调用该方法的对象。
let obj = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name); // 输出 Hello, John
}
};
obj.greet();- 在构造函数中使用
this:
在构造函数中,this 指向新创建的对象实例。
function Person(name) {
this.name = name;
}
let person = new Person('John');
console.log(person.name); // 输出 John- 在箭头函数中使用
this:
在箭头函数中,this 是静态的,它会捕获其自身作用域可访问的 this 值。
let obj = {
name: 'John',
greet: function() {
let arrowFunction = () => {
console.log('Hello, ' + this.name); // 输出 Hello, John
};
arrowFunction();
}
};
obj.greet();- 在事件监听函数中使用
this:
在事件监听函数中,this 通常指向监听事件的 DOM 元素。
<button id="myButton">Click me</button>
document.getElementById('myButton').addEventListener('click', function() {
console.log(this); // 输出按钮 DOM 元素
});- 在回调函数中使用
this:
在回调函数中,this 的值取决于回调函数被调用的方式。
let obj = {
name: 'John',
greet: function() {
setTimeout(function() {
console.log('Hello, ' + this.name); // 输出 Hello, undefined
}, 100);
}
};
obj.greet();为了在回调函数中保持 this 的值,通常有以下几种方法:
- 使用箭头函数捕获
this。 - 在调用回调之前将
this赋值给一个变量,并在回调中使用这个变量。 - 使用
Function.prototype.bind来绑定this的值。
let obj = {
name: 'John',
greet: function() {
setTimeout(() => {
console.log('Hello, ' + this.name); // 输出 Hello, John
}, 100);
}
};
obj.greet();- 在
call、apply和bind方法中使用this:
Function.prototype.call、Function.prototype.apply 和 Function.prototype.bind 方法可用于更改函数的 this 值并调用函数。
let obj = {
name: 'John',
评论已关闭