代码之家  ›  专栏  ›  技术社区  ›  mvbl fst

Javascript:Object的this.var在jQuery方法中

  •  2
  • mvbl fst  · 技术社区  · 14 年前

    我有一个功能,例如。

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

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

    5 回复  |  直到 14 年前
        1
  •  2
  •   nickf    14 年前

    在函数内部,“this”是被单击的元素,这与函数外部的“this”不同。一个简单的解决方案:

    function test () {
      this.rating = 0;
      var self = this;
      $j('#star_rating a').click(function() {
        alert(self.rating);
      });
    }
    
        2
  •  5
  •   Peter Ajtai    14 年前

    在里面 .click() this 指单击的项。所以上下文与设置时不同 rating . 那两个 s是不同的。

    你需要以某种方式保留上下文。

    另外,你可能想 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

        3
  •  1
  •   staticsan    14 年前

    如果你想保留一个 this 可能意味着别的,这是一个常见的技巧 到本地实例变量。我用 self .

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

    全部的 自己

        4
  •  1
  •   Ruan Mendes    14 年前

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

    test是一个全局函数,因此,“this”是对window(global)对象的引用。实际上,您所做的是设置一个全局变量,可能不是预期的副作用。(使用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
  •  0
  •   Douglas    14 年前

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