返回
JS中this指向详解,打破常规认识,全面解析this指向规则
前端
2023-09-18 18:31:13
this指向详解
一、全局执行环境
在全局执行环境中,也就是任何函数的外部,this都是指向全局对象。在浏览器环境下,window对象即是全局对象。
console.log(this); // 全局执行环境中的this指向window对象
二、函数执行上下文
在函数执行上下文中,this指向函数的执行对象。这个执行对象可以是全局对象、函数所属的对象、或者其他对象。
function foo() {
console.log(this); // 函数执行上下文中的this指向函数的执行对象
}
foo(); // 全局执行环境下,this指向window对象
var obj = {
foo: foo
};
obj.foo(); // obj对象作为foo函数的执行对象,this指向obj对象
三、对象方法
当作为对象的方法调用时,this指向该对象。
var obj = {
name: 'John Doe',
greet: function() {
console.log(this.name); // 对象方法中的this指向该对象
}
};
obj.greet(); // 'John Doe'
四、箭头函数
箭头函数没有自己的this,它的this指向父级作用域的this。
var obj = {
name: 'John Doe',
greet: () => {
console.log(this.name); // 箭头函数中的this指向父级作用域的this
}
};
obj.greet(); // 'John Doe'
五、事件处理程序
在事件处理程序中,this指向触发事件的元素。
document.getElementById('button').addEventListener('click', function() {
console.log(this); // 事件处理程序中的this指向触发事件的元素
});
六、构造函数
在构造函数中,this指向新创建的对象。
function Person(name) {
this.name = name;
}
var person = new Person('John Doe');
console.log(person.name); // 'John Doe'
七、类方法
在类方法中,this指向类的实例。
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(this.name); // 类方法中的this指向类的实例
}
}
var person = new Person('John Doe');
person.greet(); // 'John Doe'
八、严格模式
在严格模式下,this不能指向undefined。
"use strict";
function foo() {
console.log(this); // 在严格模式下,this不能指向undefined
}
foo(); // TypeError: Cannot read properties of undefined (reading 'name')
结语
以上就是JavaScript中this指向的全面解析。掌握this指向的规则,可以帮助你编写出更优雅、健壮的代码。