gpt4 book ai didi

javascript - 对象方法中的 "this"与事件处理程序中的 "this"

转载 作者:搜寻专家 更新时间:2023-11-01 04:49:01 24 4
gpt4 key购买 nike

编辑
答案指出关键字 this 在 jQuery 中使用,就像在任何 JavaScript 代码中一样。也就是说,对象方法接收对象本身作为 this,这就是 $.fn 函数(它们在 jQuery 对象上调用)所发生的情况。事件处理函数是回调函数,它们不是对象方法,由调用者决定 this 将在函数内部引用什么。它通常引用 DOM 元素。

原始问题

this$(this) 之间的区别通常被解释为 this 引用了一个 DOM 对象,而 $(this) 引用一个 jQuery 对象(一个带有 jQ​​uery 包装器的 DOM 元素)。
在下面的示例中,处理函数作为 DOM 元素传递给 this,通过将其包装在 $() 中,我们从中创建了一个 jQuery 对象,因此我们可以使用$.fn 命名空间中的函数。

$('div').on('click', function(event){
event.preventDefault();
$(this).css('backgroundColor', 'red');
});


但是,我刚刚在 learn.jquery.com 上看到了这个解释:

Plugins | jQuery learning center

$.fn.greenify = function() {
this.css( "color", "green" );
};
$("a").greenify(); // makes all the links green

// Explanation provided by the author of the article:
// "Notice that to use css(), another method, we use this, not $( this ).
// This is because our greenify function is a part of the same object as css()."


这是否意味着 this 在传递给事件处理函数时引用 DOM 对象,但在传递给 jQuery 对象方法时引用 jQuery 对象?
事实上,这是有道理的,因为该方法是在 jQuery 对象上调用的,因此将 jQuery 对象传递给它是合乎逻辑的。

最佳答案

“this”标识符与 jQuery 无关,它是 javascript 的组成部分。

您可以查看此链接,其中提供了“this”关键字的详细说明:http://www.devign.me/javascript-this-keyword/

关于javascript - 对象方法中的 "this"与事件处理程序中的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069612/

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