var $ this = this的原因是什么?

编程入门 行业动态 更新时间:2024-10-25 22:36:11
本文介绍了var $ this = this的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不是最好的jquery,我遇到了一个var初始化,我不知道编写代码的人为什么会这样做。

I'm not the best at jquery and I came across a var initialization that I don't know why the person who wrote the code did it this way.

在插件的init中,我们有

In the init for a plugin, we have

this.init = function(settings) { var $this = this; this.s = { initialSlide: 0, firstSlide: true, }; ... more code, some uses $this, some uses "this" }

那么$ this和this之间有什么区别?为什么不一直使用一个或另一个?

So what is the difference here between "$this" and "this" and why not use one or the other all the time?

推荐答案

通常,这意味着此的副本。关于这个的事情是它在每个函数中都会发生变化。但是,以这种方式存储会使 $ 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大量使用魔法这个值。

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 }); };

更多推荐

var $ this = this的原因是什么?

本文发布于:2023-11-26 03:19:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632421.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原因   var

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!