简体   繁体   English

处理'this'变化的最佳方法

[英]The best way to handle a change in 'this'

A problem I regularly come across writing javascript using jQuery is that when a method of an object involves adding an event listener 'this' changes from being a reference to the object, to being a reference to the DOM element that triggered the event. 我经常遇到使用jQuery编写javascript的一个问题是,当一个对象的方法涉及添加一个事件监听器'this'从对该对象的引用变为对触发该事件的DOM元素的引用。

Currently if I want to refer to the object from within the event handler I do something like this: 目前,如果我想从事件处理程序中引用该对象,我会执行以下操作:

var theObject = this;
$('selector').click(function() {
   theObject.methodToApply();
   $(this).css('background','red');
});

Is there a better way to handle the fact that events always want to reassign 'this' 是否有更好的方法来处理事件总是要重新分配'这个'的事实

What your doing is the standard way of dealing with it in jQuery. 你在做什么是在jQuery中处理它的标准方法。 The next version of jQuery will give you the ability to define what you want the this context to be. jQuery的下一个版本将使您能够定义您希望此上下文的内容。 Read Brandons blog post for more info. 阅读Brandons博客文章了解更多信息。

The reason why this changes is because of how javascript scoping works. 这种变化的原因是因为javascript作用域的工作原理。 It is better to understand this fundamental concept if you want to do any serious js. 如果你想做任何严肃的js,最好理解这个基本概念。

Explanation of this concept here: 这里概念的解释:

jQuery/JavaScript "this" pointer confusion jQuery / JavaScript“这个”指针混乱

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM