普通函数中 this
- 代表着它的直接调用者,谁调用就指向谁
- 默认情况下,没有直接调用者,this 指向 window
- 严格模式下(设置了'use strict'),this 为 undefined
- 当使用 call,apply,bind(ES5 新增)绑定的,this 指向绑定对象
声明式 --- 指向的是window
function fun1(){
console.log(this);
}
fun1();
匿名函数/赋值式 --- 指向的是window
const fun2 = function(){
console.log(this);
}
fun2();
定义在对象中的函数 --- 指向的是对象
const obj = {
fun3:function(){
console.log(this);
}
}
obj.fun3();
绑定的事件处理函数
const oDiv = document.querySelector('div');
// oDiv.onclick = function(){
// console.log(this);
// }
oDiv.addEventListener('click' , function(){
console.log(this);
})
箭头函数中 this
- 默认指向定义它时,所处上下文的对象的 this 指向; 即 ES6 箭头函数里 this 的指向就是上下文里对象 this 指向,偶尔没有上下文对象,this 就指向 window
例子1
const obj = {
// 普通函数,this指向调用它的对象
fun1: function() {
console.log(this)
},
// 箭头函数this指向是父级程序
// 父级程序是对象
// 只有函数有this,obj对象没有this
// 父级程序没有this,指向的是window
fun2: () => {
console.log(this)
},
// fun3是一个普通函数,this指向的是obj对象
fun3: function() {
// fun4,是一个箭头函数,this指向的是父级程序的this指向
// 父级程序是fun3
// fun3的this是对象,fun4箭头函数的this也是对象
const fun4 = () => {
console.log(this)
}
fun4()
}
}
obj.fun1()
obj.fun2()
obj.fun3()
例子2
var x=11;
var obj={
x:22,
y:this, //window
say:()=>{
console.log(this.x);
}
}
obj.say(); // 输出的值为11
console.log(obj.y); // 输出的值为window对象
obj 对象中的 this 指代的就是 window,也就是全局环境,因为箭头函数中的 this 就会就近找到上一个对象中 this 所指代的对象,从以上例子可以看出来,obj 内部属性 y 就为 obj 内部 this 指代的对象,输出是window。