博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
var $this = $(this)
阅读量:5160 次
发布时间:2019-06-13

本文共 1884 字,大约阅读时间需要 6 分钟。

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.

 

 

 

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

 

在很多地方,我们都会看到

var $this = $(this)的代码,那它到底是什么意思,有什么用呢?

this其实是一个html 元素。

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

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

 

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

你可能感兴趣的文章
MYSQL逆向工程generatorConfig
查看>>
Microsoft Visual Studio 2010(vs10)安装与使用
查看>>
sitecore系列教程之Sitecore个性化-体验概况概述
查看>>
【洛谷】P1876 开灯
查看>>
本周总结
查看>>
关于“/”应用程序中的服务器错误 之解决方案
查看>>
php编译安装参数说明
查看>>
Windows推包脚本
查看>>
多表查询
查看>>
单表查询
查看>>
网络并发 数据库可能的面试题
查看>>
mysql 之多表查询
查看>>
MySQL之视图、触发器、事务、存储过程、函数
查看>>
Navicat工具、pymysql模块
查看>>
MySQL之索引原理与慢查询优化
查看>>
MySQL之锁、事务、优化、OLAP、OLTP
查看>>
MySQL之创建用户和授权
查看>>
学生选课系统
查看>>
高大上版解决粘包问题
查看>>
什么是粘包,如何解决?
查看>>