【问题标题】:Keep "this" in a variable and replace all "this" with this variable?将“this”保留在变量中并用该变量替换所有“this”?
【发布时间】:2012-09-03 15:19:15
【问题描述】:

上下文

当我使用 jQuery 时,我经常需要将this 保存在一个变量中:

var obj = {
    myVar: null,
    myFunction1: function() { ... },
    myFunction2: function() {
        this.myVar = "blabla";
        this.myFunction1();

        var ctx = this;
        $('xxx').click(function () {
            ctx.myFunction1();
        });
    }
}

在这种情况下,我将所有 this 替换为我的变量:

var obj = {
    myVar: null,
    myFunction1: function() { ... },
    myFunction2: function() {
        var ctx = this;

        ctx.myVar = "blabla";
        ctx.myFunction1();

        $('xxx').click(function () {
            ctx.myFunction1();
        });

        //etc. I do it for all "this" even if I have 15 "this"...
    }
}

问题

  • this 保留在变量中是一种好习惯吗?还有其他方法吗?
  • 用变量替换所有this 是否是个好习惯?

【问题讨论】:

    标签: javascript jquery coding-style this readability


    【解决方案1】:

    this 在不同的功能中是不同的。在那种情况下,上下文是不同的。

    因此,将其保存在一个单独的变量中是明智的,这样您就可以确定您正在与什么上下文对话。

    在有子函数的函数中,我建议这样做,在常规函数中不要这样做。那里没有必要。

    注意:你不能替换它,你只是有一个指向正确上下文的指针。

    【讨论】:

      【解决方案2】:

      还有其他方法吗?

      你可以使用$.proxy [docs]:

      $('xxx').click($.proxy(function () {
          this.myFunction1();
      }, this));
      

      这显然会覆盖事件处理程序中的this,因此您无法通过this 访问该元素。

      您也可以将this 传递为event data [docs]

      $('xxx').click({ctx: this}, function (event) {
          event.data.ctx.myFunction1();
      });
      

      做任何你认为最易读的事情。我个人只是分配 var self = this; 并在嵌套函数中使用 self 并在其他任何地方使用 this

      【讨论】:

        【解决方案3】:

        还有其他方法吗?

        是的:您可以使用匿名自执行函数将引用传递给作用域

        myFunction2: function() {
            this.myVar = "blabla";
            this.myFunction1();
        
            (function(outerscope) {
                $('xxx').click(function () {
                    outerscope.myFunction1();
                });
            }(this));
         }
        

        无论如何,像您一样存储引用是可以的(或者至少,google javascript style guide 不鼓励将其作为一种不好的做法),并且这是一种广泛使用的常见做法。

        【讨论】:

          【解决方案4】:

          我总是用来创造:

          var _self = this;
          

          说实话,我不知道这是否是最佳实践,但自从我用 js 编写代码后,我看到很多人都在这样做,我觉得使用它很舒服。

          【讨论】:

          • ye,你可以使用任何你想要和喜欢的东西。
          【解决方案5】:

          这通常是一种公认​​的模式,但是当您在函数内(在 func-functions-tions 内 ;-) 等中有函数时,它可能会让人感到困惑

          缓解这种情况的一种方法(以及一般的替代方法)是将您的函数绑定到特定的上下文对象。 ECMAScript 5's bind() function 处理这个问题,但在 Web 环境中使用可能还不安全。

          现在你可以改用jQuery's proxy function:

              $('xxx').click(jQuery.proxy(function () {
                  this.myFunction1();
              }, this));
          

          【讨论】:

            猜你喜欢
            • 2011-07-26
            • 2019-04-12
            • 2012-12-12
            • 1970-01-01
            • 1970-01-01
            • 2012-08-11
            • 2011-01-14
            • 1970-01-01
            • 2012-10-30
            相关资源
            最近更新 更多