this 的指向,可以分为两个大类:
- 函数外部:永远指向全局对象(window);
- 函数内部,分为两种情况:
- 箭头函数:箭头函数中没有 this,如果要在箭头函数中使用 this,实际上使用的就是箭头函数所在作用域中的 this。
- 非箭头函数:谁调用的该函数,函数中的 this 就指向谁;
函数内部的 this
1、普通函数
普通函数,就是函数本身创建时不是箭头函数,调用时直接通过 函数名() 调用,这样的就属于普通函数。
结论:普通函数的 this 指向 window。function foo() {console.log(this); // window}foo();
2、对象方法
结论:对象方法的 this,指向调用该方法的对象。const student = {name: '张三',sayHello: function () {console.log(this);}}const person = {name: '李四'};person.sayHello = student.sayHello;student.sayHello(); //student{}person.sayHello(); //person{}
3、事件处理函数
结论:原生 JS 事件处理函数中的 this,指向的是绑定事件的元素节点。const father = document.getElementById('father');father.addEventListener('click', function() {console.log(this); // father})
4、构造函数、class
结论:构造函数或 class 中的 this,指向 new 出来的实例对象。function Person() {console.log(this);}const person = new Person(); // personclass Student {constructor() {console.log(this);}}const student = new Student(); // student
5、箭头函数
结论:箭头函数中没有 this。如果要在箭头函数中使用 this,实际上使用的就是箭头函数所在作用域中的 this。const student = {name: '张三',sayHello: function() {const foo = () => {console.log(this);}foo();}}student.sayHello(); //student{}
6、jquery 事件处理函数
结论:jQuery 事件处理函数中的 this,指向的是触发事件的元素(表示有可能是子元素等)。$('#father').on("click", function() {console.log($(this));})
