var $this = $(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

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

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

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

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

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(590)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2015-07-10 Linq中的常用方法
2015-07-10 Good vs Evil
2015-07-10 What code you will get when you create a wcf library
2015-07-10 几种方法的尾递归实现
2014-07-10 Win7系统中如何查看当前文件被哪一个程序占用了
点击右上角即可分享
微信分享提示