Javascript scope problem with object and setTimeout
<p>I'm trying to make a jQuery plugin that executes a method on a timer. I'd like it to work on multiple elements on a page independently. I've reached a point where the timer executes for each element, but the method called in the setTimeout seems to only know about the last instance of the plugin.</p>

<p>I know I'm doing something fundamentally stupid here, but I'm danged if I know what. I know stuff like this has been asked 8 million times on here before, but I've not managed to find an answer that relates to my specific problem.</p>

<p>Here's a script that demonstrates the structure of what I'm doing.</p>

<pre><code>&lt;html&gt;
&lt;head&gt;
&lt;script type="text/javascript" src="assets/jquery.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
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();
});
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class="wahey"&gt;&lt;/div&gt;
&lt;div class="wahey"&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>The output I get is this:</p>

<pre><code>0
1
1
1
1
1
</code></pre>

<p>The output I expect to get is this:</p>

<pre><code>0
1
0
1
0
1
</code></pre>
