gpt4 book ai didi

javascript - forEach 和 addEventListener 方法中 "this"的行为

转载 作者:行者123 更新时间:2023-12-02 23:18:54 25 4
gpt4 key购买 nike

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

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

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

this引用全局对象,因为该函数绑定(bind)到全局对象,但是当我使用时:

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

thisid元素,即使它在函数内?是不是因为forEach是数组的方法而不是对象的方法?

最佳答案

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

关于javascript - forEach 和 addEventListener 方法中 "this"的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57036483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com