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

标签 javascript jquery jquery-plugins

编辑
答案指出关键字 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/

相关文章:

jquery - jquery 中的下拉子菜单出现问题

javascript - 删除输入文本的 Chrome 样式(列表)

javascript - 当 div 清空时,Ajax 加载的弹出图像并不总是清除

javascript - Jquery 只针对 child 而不是子 child

javascript - Ext.Ajax.request在jQuery.ajax发送GET时发送OPTIONS请求跨域

jquery - 如何在jQuery Expander插件中使用jQuery的 "slideDown"和 "slideUp"效果?

javascript - jQuery UI布局插件OVERFLOW设置

jQuery 网页预览

javascript - 使用 Ajax 查询数据库

javascript - VueJS : React to State change through mapGetters receiving arguments