views:

52

answers:

1

When i run this code alert 2 shows 6 different href links. alert 3 shows the last href 6 times. How do i make it use the same object (linkdom aka thelink) as alert 2.

NOTE: This is in a greasemonkey script

    {
        var linkdom = thelink;
        alert('2' + linkdom.getAttribute("href"));
        GM_xmlhttpRequest({
            method: 'GET',
            url: href,
            onload: function(resp){
                //...
                alert('3' + linkdom.getAttribute("href"));
            }
        });
    //...
    }
+1  A: 

If this were your own function, I'd say to pass it in as a parameter. Or if JavaScript had default parameters, I'd say pass it in as a default parameter. The way it is now, though... try this.

{
    var linkdom = thelink;
    alert('2' + linkdom.getAttribute("href"));        
    GM_xmlhttpRequest({
        method: 'GET',
        url: href,
        onload: (function() { 
              var localvar = linkdom; 
              return function(resp){
                //...
                alert('3' + localvar.getAttribute("href"));
              }})()
    });
//...
}

This creates an outer function and sets a local variable to the current value of linkdom. It then creates your function and returns it. I then immediately apply the outer function to get your function back. The outer functions won't share the same local variable, so the code should work.

Claudiu
i've seen this pattern before, except `linkdom` is passed to the inline function as a parameter, rather than having the inline function close over it. is there any difference between the two?
lincolnk
im not sure. i think the effect is the same - create a local variable with what you want in it. this way is a bit clearer to me since you can see what goes into `localvar` more clearly
Claudiu