JavaScript教程:this关键字

说明

this 关键字,表示当前对象,通过 this 关键字可以访问 当前对象的属性

关于 “我” 的理解

李雷说:“我叫李雷”,此处的 我 表示李雷

韩梅梅说:“我考了90分”,此处的 我 表示韩梅梅

每个人说的 我,我 表示说话人自己

关于 this 的理解

this 相当于 我,表示当前对象

每个对象都有 this,this 表示的是当前这个对象

案例 - 全局中的this

在全局作用域中,this 指向 window 对象

<script>
   console.log(this); //this->window
</script>

案例 - 普通函数中的this

在普通函数中,this 指向 window 对象

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

案例 - 定时器中的this

定时器中,this 指向 window 对象

setInterval(function() {
    console.log(this);
},500)

案例 - 事件绑定中的this

写法一:

事件源.onclik = function(){ } //this 指向 事件源

写法二:

事件源.addEventListener(function(){ }) //this 指向 事件源

例子:

var btn = document.querySelector('button');

// 写法一
btn.addEventListener('click',function() {
    console.log(this); //this 指向按钮
});

// 写法二
btn.onclick = function() {
    console.log(this) //this 指向按钮
}

案例 - 自定义对象中的this

定义对象,有 age 属性,有 grow 长大方法,调用 grow() 方法时,让 age 属性加1

<script>
    let student = {
        age:20,
        grow:function(){
            console.log("grow() 中的this:",this)
            // 通过this,访问 age 属性。没有this,表示访问全局变量或局部变量
            this.age ++
            console.log("长大一岁,今年:",this.age)
        }
    }

    student.grow()

</script>

参考:
https://blog.csdn.net/chen_junfeng/article/details/109235442


原文出处:/show_1IX3BvgB7iFi.html