浅谈关于this的指向问题

    button {
        width: 100px;
        height: 100px;
        background-color: rebeccapurple;
    }



<button id="attackBtn">
    打人
</button>
<button id="startTimerBtn">
    开启定时器
</button>
<script>
    class Peopole {
        constructor(dataObj) {
            this.name = dataObj.name;
            this.age = dataObj.age;
            this.sex = dataObj.sex;
            $("#attackBtn").click(this.attack.bind(this))
            $("#startTimerBtn").click(this.startTimer.bind(this))
        }
        //这里的一级函数this指的是对象本身
        runEvent() {
            console.log("我叫:''" + this.name + "'今年'" + this.age + "'岁了" + "我在跑步,对了我还是'" + this.sex + "'孩子喔")
        }
        //这里的点击事件 this指的是处罚该函数的按钮对象
        attack() {
            console.log("我是'" + this.name + "'我在打架")
        }

        //开启定时器的方法
        startTimer() {
            console.log("开启了定时器")
            // var that=this;
            var timer=setInterval(function()
            {
                console.log("1")
                console.log(this.name)
            }.bind(this),500)
        }

    }
    var dataObj =
    {
        name: "郭嘉",
        age: "15",
        sex: "男"
    }
    var m = new Peopole(dataObj)
    m.runEvent()
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章