var $ this = this的原因是什么? [英] What is the reason for var $this = this

查看:219
本文介绍了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的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆