JavaScript中this指向的总结


JavaScript中this指向的总结

1、传统普通函数

this指向调用者

例如:

function test(){
     console.log(this)
}
test()  // 指向window
function Person() {
	test() {
		console.log(this)
	}
}
let person = new Person()
person.test() // 指向person

2、使用call和apply的普通函数

call和apply传入什么对象就指向什么对象

例如:

var obj = {}
function test() {
	console.log(this)
}
test().call(obj)  //指向obj
test().apply(obj) //指向obj

3、es6的箭头函数

this指向外层作用域,啥意思呢,看如下的例子
let p ={
    name:"黄超",
    test: {
        test1: {
            aa:()=> {
                console.log(this)
            }
        }
    }
}
p.test.test1.aa() // 指向window
let aa ={
    name:"黄超",
    test: {
        test1: {
            test2() {
                let a = 2
                let b = 3;
                (()=>{
                    console.log(this)
                })()
            }
        }
    }
}
aa.test.test1.test2() //指向test1这个对象
let person = {
    name:"hc",
    garde:[12,14,15,16],
    test() {
        let index = -1
        return {
            aa:()=>{
                console.log(this)
            }
        }
    }
}
person.test().aa() // 指向person
因此,简单总结一下就是,箭头函数的this指向的是它作用域外层的哪个对象,怎么理解它的作用域呢,可以简单的理解为离它最近的那个中执行代码的那个作用域