var $ this = this的原因是什么?

hog*_*olo 18 javascript variables jquery this

我不是jquery中最好的,我遇到了var初始化,我不知道编写代码的人为什么会这样做.

在插件的init中,我们有

this.init = function(settings) {
    var $this = this;
    this.s = {
        initialSlide: 0,
        firstSlide: true,
    };
   ... more code, some uses $this, some uses "this"
}
Run Code Online (Sandbox Code Playgroud)

那么"$ this"和"this"之间有什么区别,为什么不一直使用一个或另一个呢?

pim*_*vdb 33

通常,这意味着副本this.关键this是它在每个功能中都会发生变化.然而,以这种方式存储它不会$this改变,而是this会改变.

jQuery大量使用魔术this值.

考虑一下这段代码,您可能需要这样的代码:

$.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
    });
};
Run Code Online (Sandbox Code Playgroud)


Jus*_*ner 6

在这种情况下,没有.$this只是另一个this分配给它的变量声明.

通常,我已经看到了人们在换行时使用JavaScript库时使用的这种快捷方式this.例如,jQuery中的典型用法是:

// rather than writing $(this) everywhere
var $this = $(this);

$this.each(function(){
    // Do Something
});
Run Code Online (Sandbox Code Playgroud)