this属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="box">box</div>
    <script>
        // this js的一个关键字,这个对象,在不同的使用场景代表不同对象
        // this的第一种使用场景:对象方法里的this就是当前对象本身
        var obj = {
            name:'张三',
            say:function(){
                // this就是 “我” 的意思
                console.log(this.name)
            }
        }
        obj.say()

        console.log(obj.name)
        // 删除对象的属性
        delete obj.name
        console.log(obj.name)

        // this的第二种使用场景:事件里的this指向事件触发对象
        var box = document.getElementById('box')
        box.onclick = function () {
            console.log(this)
            this.style.background = 'red'
        }
    </script>
</body>
</html>
发布了60 篇原创文章 · 获赞 3 · 访问量 539

猜你喜欢

转载自blog.csdn.net/dfc_dfc/article/details/105499377
今日推荐