var $this = $(this) 亦凉 2021-11-29 18:56 248阅读 0赞 # [jQuery: What’s the Difference Between $(this), $this, and this?][jQuery_ What_s the Difference Between _this_ _this_ and this] # ### What about $this? ### $this is a little different because it’s actually just a variable that uses the $. It has no inherent relation to jQuery. It would be no different than JavaScript variables named $corn or $carrots. You just was easily say var $this = “My pet cat is named Mittens.”; It’s just a variable with the dollar sign in it. JavaScript allows characters like this in variable names. The reason that you see use of $this inside of jQuery plugins is that often times developers in the global scope **inside of their plugin** will say something like: var $this = $(this); That way they can always have a reference to the object on which the plugin was called. The scope of “this” will change in any methods used inside the plugin so it’s always good to have a global variable (that is, global inside the plugin scope) which you can refer to the object on which the plugin was called. But the important thing to remember is that $this has no inherent relation to jQuery. It’s just a variable like any other. # [What is the reason for var $this = this][What is the reason for var _this _ this] # Generally, this means a copy of `this`. The thing about `this` is that it changes within each function. Storing it this way, however, keeps `$this` from changing whereas `this` does change. jQuery heavily uses the magic `this` value. Consider this code, where you might need something like you are seeing: $.fn.doSomethingWithElements = function() { var $this = this; this.each(function() { // `this` refers to each element and differs each time this function // is called // // `$this` refers to old `this`, i.e. the set of elements, and will be // the same each time this function is called }); }; # [https://blog.csdn.net/mxt123456/article/details/53152398][https_blog.csdn.net_mxt123456_article_details_53152398] # 在很多地方,我们都会看到 var $this = $(this)的代码,那它到底是什么意思,有什么用呢? this其实是一个html 元素。 $this 只是个变量名,加$前缀是为说明其是个jquery对象。 而$(this)是个转换,将this表示的dom对象转为jquery对象,这样就可以使用jquery提供的方法操作。 作用:把当前对象保存起来,便于后边的使用。 转载于:https://www.cnblogs.com/chucklu/p/11164158.html [jQuery_ What_s the Difference Between _this_ _this_ and this]: http://www.9bitstudios.com/2013/03/jquery-whats-the-difference-between-this-this-and-this/%20 [What is the reason for var _this _ this]: https://stackoverflow.com/questions/7234282/what-is-the-reason-for-var-this-this [https_blog.csdn.net_mxt123456_article_details_53152398]: https://blog.csdn.net/mxt123456/article/details/53152398
还没有评论,来说两句吧...