var $this = $(this)

博客主要探讨了jQuery中$(this)、$this和this的区别。this是HTML元素,$this是变量名,加$前缀表明是jQuery对象,$(this)是将DOM对象转为jQuery对象以便使用其方法。使用var $this = $(this)可保存当前对象,方便后续使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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.youkuaiyun.com/mxt123456/article/details/53152398

在很多地方,我们都会看到
var $this = $(this)的代码,那它到底是什么意思,有什么用呢?

this其实是一个html 元素。
$this 只是个变量名,加$前缀是为说明其是个jquery对象。
而$(this)是个转换,将this表示的dom对象转为jquery对象,这样就可以使用jquery提供的方法操作。

作用:把当前对象保存起来,便于后边的使用。

 

转载于:https://www.cnblogs.com/chucklu/p/11164158.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值