淺談關於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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章