【问题标题】:Javascript: Object's this.var inside jQuery methodJavascript:对象在 jQuery 方法中的 this.var
【发布时间】:2010-10-19 23:16:05
【问题描述】:

这个我想不通:

我有一个函数,例如

功能测试 () { this.rating = 0; $j('#star_rating a').click(function() { 警报(this.rating); }); } var foo = new test();

点击它会提示“未定义”。怎么了?请帮忙。

【问题讨论】:

    标签: javascript jquery oop


    【解决方案1】:

    .click() 内,this 指的是点击的项目。因此上下文与您设置rating 时不同。这两个thiss 是不同的。

    您需要以某种方式保存上下文。

    另外,如果您单击链接并且不想刷新页面,您可能需要return false;event.preventDefault()

    function test () {
    
      this.rating = 0;
      var oldThis = this;           // Conserving the context for use inside .click()
    
      $j('#star_rating a').click(function() {
    
           alert(oldThis.rating);
    
           return false; // Use this if you don't want the page to change / refresh
      });
    }
    
    var foo = new test();
    

    Try it out with this jsFiddle

    【讨论】:

      【解决方案2】:

      在函数内部,“this”是被点击的元素,与函数外部的“this”不同。一个简单的修复:

      function test () {
        this.rating = 0;
        var self = this;
        $j('#star_rating a').click(function() {
          alert(self.rating);
        });
      }
      

      【讨论】:

        【解决方案3】:

        如果您想在对象内部保留类似this 的引用以供以后使用,而this 可能意味着其他含义,将this 分配给本地实例变量是一个常见的技巧。我使用self

        function test () {
          var self = this;
          self.rating = 0;
          $j('#star_rating a').click(function() {
            alert(self.rating);
          });
        }
        
        var foo = new test();
        

        这个技巧的优点是在你的对象中的 all 代码 - 甚至是闭包 - self 将始终引用该对象。您也可以使用this 来指代通常的含义。

        【讨论】:

          【解决方案4】:

          正如其他人所说,“this”在测试和传递给 click() 的匿名函数中有所不同。

          test 是一个全局函数,因此,“this”是对窗口(全局)对象的引用。您实际上在做的是设置一个全局变量,可能不是预期的副作用。 (使用 alert(window.rating) 来了解我的意思)

          对于您的示例,无需使用“this”,尽管我认为您的示例只是为了说明一个观点。如果是真实代码,tt应该转换为:

          function test () {
            var rating = 0;
            $j('#star_rating a').click(function() {
              alert(rating); //Use the closure defined in the outer function
            });
          }
          

          关键是你不应该在全局函数中使用“this”。

          【讨论】:

            【解决方案5】:

            this 在这两种情况下都不同。尝试在 firebug 中使用断点来查看它们的设置。

            【讨论】:

              猜你喜欢
              • 2012-11-05
              • 1970-01-01
              • 2012-06-24
              • 2015-07-13
              • 1970-01-01
              • 2012-06-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多