3 回答

TA贡献1863条经验 获得超2个赞
您不能将“this”对象作为匿名函数中的参数传递。当你这样做时,如果你认为你有约束力,你就错了。当您使用Anonymus键入函数时,“this”会自动显示窗口对象,是的。
注1:没有箭头函数的构造函数或原型。它不与新的一起使用。目的不是创建对象实例。
注意2:由于2个箭头函数不会将自己绑定到“this”绑定词法范围上下文不会自动绑定自身。
let clicked = () => {
console.log(this) // *"this"* will always show the window object because it was written with arrow function.
}
let clicked = function(){
console.log(this) // *"this"* will show the" p " element. Because bind inte.
}
document.querySelector("#p").addEventListener("click", clicked)
document.querySelector("#p").addEventListener("click", clicked.bind(this)) // If you do bind this way and call the clicked function, which is defined as the arrow function, *"this"* window will show the object.
<p id="p" onclick="myFunc(this)">foo</p> // The reason this works is because it shows the element when you say *"this"*. but the function is in scope if you look at the console.log(this) output, it will show the window object.
function myFunc(el){
console.log(el.innerHTML) // outputs "foo"
console.log(this) //
}
因此,您不能在箭头函数中重新绑定“this”。它将始终被定义为定义它的上下文。如果你要求这有意义,你应该使用一个普通的函数。
我希望这有点启示。

TA贡献1810条经验 获得超5个赞
addEventListener eventTarget 需要第二个参数作为 eventHandler 或 jvasrcipt 函数(参见 ref)。因此,如果您将HTML对象作为第二个参数传递,您将获得一个语法错误:“缺少正式参数”,并且您的代码将不会运行(检查浏览器控制台)。为了回答您的其他查询,在本例中,这是一个 HTML p 对象。您可以检查自己:
console.log(this);
console.log(typeof this);

TA贡献1780条经验 获得超1个赞
我以前也有过这样的疑问。
这主要是因为箭头函数与普通函数不同,并且在其中一些差异中,“this”在两者中都受到不同的对待。
“那这个呢?与常规函数相比,箭头函数对此的处理也不同。简而言之,使用箭头函数没有绑定。在常规函数中,this 关键字表示调用函数的对象,可以是窗口、文档、按钮或其他任何内容。对于箭头函数,this 关键字始终表示定义箭头函数的对象。
字体: https://www.w3schools.com/js/js_arrow_function.asp
添加回答
举报