函数上下文判断规律(this指向)

ES5中函数上下文判断规律:看调用执行

1、函数名加小括号调用  全局 window

2、定时器、延迟器  全局 window

var o = {
    a() {
        console.log(this)   //o
        setTimeout(function () {
            console.log(this)   //window
        })
        setTimeout(() => {
            console.log(this)   //o
        })
    }
}
o.a()

3、函数作为事件处理函数  触发这个事件的节点

document.getElementById('div').onclick = function () {
    console.log(this)   //div元素
}

4、函数作为对象的方法,谁最后打点调用,上下文就是谁

5、函数作为数组元素枚举出来执行  当前数组

function fun1() {
    console.log(this.length)
}
function fun2(a, b) {
    a(b)
}
function fun3(a, b) {
    arguments[0](b)
}
fun2(fun1, 1, 2, 3, 4, 5)   //0 this指代window
fun3(fun1, 1, 2, 3, 4, 5)   //6 this指代arguments,类数组

6、new  当前类的实例

ES6中

箭头函数  看声明时所处的函数作用域

var name = 'Smith'
var obj = {
    name: 'Jack',
    eat: {
        name: 'John',
        eat: function () {
            console.log(this.name)
        }
    }
}

obj.eat.eat()   //John
var fun = obj.eat.eat
fun()   //Smith
const name = 'Smith'
const obj = {
    name: 'Jack',
    eat: {
        name: 'John',
        eat: () => {
            console.log(this.name)
        }
    }
}

obj.eat.eat()   //Smith 箭头函数,this指向函数声明时的作用域,window
const fun = obj.eat.eat
fun()   //Smith
原文地址:https://www.cnblogs.com/lianglanlan/p/14244210.html