【问题标题】:behavior of "this" in forEach and addEventListener method [duplicate]forEach 和 addEventListener 方法中“this”的行为[重复]
【发布时间】:2019-07-15 09:06:58
【问题描述】:

编辑:这不是关于“this”关键字在不同上下文中的一般行为的问题。我的问题是,这两种行为背后是否存在共同的底层逻辑——是否因为“this”仅在调用该对象的方法时才绑定到该对象,但 forEach() 是数组的方法?
为什么我用的时候会这样:

var tag = ["a","b","c"];

tag.forEach(function () { 
  console.log(this)
});

this 指的是全局对象,因为函数绑定到全局对象,但是当我使用时:

element.getElementById("id").addEventListener("click", function () {
  console.log(this.value);
});

this 指的是id 元素,即使它在函数中?是不是因为forEach是数组的方法而不是对象的方法?

【问题讨论】:

标签: javascript object foreach this addeventlistener


【解决方案1】:

在 DOM 事件处理程序中,this 设置为触发事件的元素: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#As_a_DOM_event_handler

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    相关资源
    最近更新 更多