var $this = $(this)

亦凉 2021-11-29 18:56 325阅读 0赞

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:

  1. 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

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:

  1. $.fn.doSomethingWithElements = function() {
  2. var $this = this;
  3. this.each(function() {
  4. // `this` refers to each element and differs each time this function
  5. // is called
  6. //
  7. // `$this` refers to old `this`, i.e. the set of elements, and will be
  8. // the same each time this function is called
  9. });
  10. };

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

发表评论

表情:
评论列表 (有 0 条评论,325人围观)

还没有评论,来说两句吧...

相关阅读

    相关 this

    转自:https://segmentfault.com/a/1190000003046071 本文主要解释在JS里面this关键字的指向问题(在浏览器环境下)。 首先,必须

    相关 this

    todo 函数的this绑定在执行上下文,是执行上下文的一个属性,胖箭头根据外层(函数或全局)作用域来决定this,它的绑定无法修改 转载于:https://www.cnbl