javascript - var $this = this 的原因是什么

标签 javascript jquery variables this

我不是最擅长jquery,而且我遇到了一个var初始化,我不知道为什么编写代码的人这样做。

在插件的初始化中,我们有

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

那么“$this”和“this”之间有什么区别,为什么不一直使用其中一个呢?

最佳答案

通常,这意味着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
    });
};

关于javascript - var $this = this 的原因是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7234282/

相关文章:

javascript - jQuery + CSS,通过类似淡入淡出的过渡删除悬停时的其他图像

c++ - C++中一个变量定义列表中的常量和非常量

javascript - 页面加载时未加载 Angular-ui-router 状态

javascript - vue资源-动态判断http方法

javascript - 在新选项卡中打开 Blob Url (IE)

javascript - 无法接收从 html 中的 Rest api 传递的 json 响应

javascript - 删除 C# 列表中的空节点

javascript - 如何在 Backbone.js 中设置 View 的 id?

variables - 未找到 SGE 命令, undefined variable

javascript - 将 javascript 变量传递给 Paypal