知识点:this指向

全局环境与全局函数

    //this指向全局函数对象 window
    console.log(this)

    function fun() {
        console.log(this)
    }
    fun()

 对象


    //this指向调用该方法的对象 person
    let person1 = {
        name: '小鹿',
        todo() {
            console.log(this.name)
        }
    }
    person1.todo()

Dom事件


    // 事件中的this指向触发事件的dom对象:<button></button>
    const btn = document.querySelector("button")
    btn.onclick = function () {
        console.log(this)
    }

构造函数 

    // new关键字做了什么:用来创建对象,将创建对象的this指向创建出来的对象f
    function Fun() {
        this.name = "小鹿"
    }
    let f = Fun()
    console.log(f)

   

普通函数与箭头函数

    let person2 = {
        name: '小鹿',
        todo() {
            console.log(this)
            // 普通函数函数外指向谁就是谁
            setTimeout(function () {
                console.log(this) // window
            }, 1000)
            // 箭头函数函数外指向谁就是谁
            setTimeout(() => {
                console.log(this) // person2
            }, 1000)
        }
    }
    person2.todo() //指向person2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值