浅谈关于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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值