Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Javascript and Scope

Name: Anonymous 2010-06-10 3:17

How do I call charizard from deep within squirtle?


var pokedexObject = {
    charizard: function() {
        console.log("I am charizard.");
    },
    squirtle: function() {
       // extenral API pseudocode incoming.
1
       $("<elem>").each(function() {
           // dom create element
           var pokePic = $("<img src=\"squirtle.png\">");
           // dom attach
           $(this).append(pokePic);
           // dom event listener
           pokePic.click(function() {
               // charizard! i choose you!
               // ...but how?
           });
       });
    }
};


______________
1. This example uses external DOM API pseudocode. The reason is that in APIs like these, nested closures are common -- perfect for illustrating the problem. I have also included comments to indicate the general DOM tasks these pseudo-calls intend to describe.

Name: Anonymous 2010-06-10 5:51

>>4
That doesn't really solve the problem. Not only does >>1 need to make a method call from within another method, he needs to do it within a closure which is itself within a closure. I'm assuming it's written that way because the innermost closure is being passed as a callback for a mouse click event.

This is what I do, but I'm not sure what the "best practice" is.

var  pokedexObject = {
    charizard: function() {
        console.log("I am charizard.");
    },
    squirtle: function() {
        // wrap the current "this" context into a local variable for the following closures
        var self = this;
        // extenral API pseudocode incoming.1
        $("<elem>").each(function() {
            // dom create element
            var pokePic = $("<img src=\"squirtle.png\">");
            // dom attach
            $(this).append(pokePic);
            // dom event listener
            pokePic.click(function() {
                self.charizard();
            });
        });
    }
};

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List