2010-05-11 96 views
0

我试图做一个jQuery插件,执行定时器上的方法。我希望它能独立处理页面上的多个元素。我已经达到了定时器为每个元素执行的一点,但setTimeout中调用的方法似乎只知道插件的最后一个实例。对象和setTimeout的Javascript范围问题

我知道我在这里做了一些根本上愚蠢的事情,但是如果我知道什么的话,我就会死。我知道这样的东西在这里被问过800万次,但我没有找到与我的具体问题有关的答案。

下面是一个脚本,演示了我正在做的事情的结构。

<html> 
<head> 
<script type="text/javascript" src="assets/jquery.min.js"></script> 
<script type="text/javascript"> 
var crap = 0; 
(function($) 
{ 
    jQuery.fn.pants = function(options) { 
     var trousers = { 
      id: null, 
      current: 0, 
      waitTimeMs: 1000, 

      begin: function() { 
       var d = new Date(); 
       this.id = crap++; 
       console.log(this.id); 
       // do a bunch of stuff 
       window.setTimeout(function(self) {return function() {self.next();}}(this), this.waitTimeMs); 
      }, 

      next: function() { 
       this.current ++; 
       console.log(this.id); 
       window.setTimeout(function(self) {return function() {self.next();}}(this), this.waitTimeMs); 
      }, 
     }; 

     options = options || {}; 
     $.extend(trousers, options); 

     this.each(function(index, element) { 
      trousers.begin(); 
     }); 

     return this; 
    }; 
} 
)(jQuery); 
jQuery(document).ready(function() { 
    jQuery("div.wahey").pants(); 
}); 
</script> 
</head> 
<body> 
<div class="wahey"></div> 
<div class="wahey"></div> 
</body> 
</html> 

输出我得到的是这样的:

0 
1 
1 
1 
1 
1 

我希望得到的输出是这样的:

0 
1 
0 
1 
0 
1 

回答

0

这可能是你使用“这个”,这是浏览器的具体情况并不总是point to what you want it to point to。这属于函数的所有者,而不是函数的对象。

+0

我能做些什么来解决它? – Shabbyrobe 2010-05-11 14:01:28

+0

使用范围特定变量而不是此。在http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/附近看看它谈到的“臭名昭着的循环问题” – Malfist 2010-05-11 14:07:51