1、this
关键字
2、对象this
的指向
this的指向类型 | |
---|
1、指向调用方法的对象 | 最常用的一种情况,一个对象调用一个方法,那么方法中的this,指向这个对象 |
2、指向new创建出来的对象 | 构造函数中的this,指向new创建出来的对象 |
<script>
let person = {
name: "jasmine",
getName() { console.log(this.name); }
}
person.getName();
function person1(name) {
this.name = name;
}
let person2 = new person1("jasmine");
console.log(person2.name);
class Person3 {
constructor(name) {
this.name = name;
}
}
let person4 = new Person3("jamsine");
console.log(person4.name);
</script>
3、DOM事件this
的指向
- 当DOM事件被触发时,事件监听函数中的this指向触发事件的DOM对象
<button>按钮</button>
<script>
document.querySelector('button').onclick = function () {
console.log(this);
}
</script>
4、全局事件this
的指向
function fun() { console.log(this); };
fun();
5、普通函数与箭头函数this
的指向
类型 | this指向 |
---|
普通函数 | 指向window |
箭头函数 | 指向定义函数的上下文的this |
let person = {
name: "jasmine",
getName() { console.log(this.name); },
getName1() {
setTimeout(() => {
console.log(`箭头函数:${this}`);
}, 1000)
},
getName2() {
setTimeout(function () {
console.log(`普通函数:${this}`);
}, 1000)
}
}
person.getName();
person.getName1();
person.getName2();
总结
this 关键字 | 指向 |
---|
1、全局环境下的this | 指向全局对象(Window) |
2、全局函数中的this | 指向全局对象(Window) |
3、内部函数中的this | 指向全局对象(Window) |
4、方法中的this | 指向调用方法的对象 |
5、事件中的this | 指向触发事件的DOM对象 |
6、构造函数中的this | 指向new创建的对象 |
7、箭头函数中的this | 指向定义函数的上下文的this |