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:26

>>1
IIRC, In Javascript an "object" is basically a hash table, and doesn't have an "object-level scope", therefore you can't refer to charizard directly if you use the literal syntax. You can get this to work if you use a different method for object creation,
function pokedexObject() {
  this.charizard = function() {
    console.log("I am charizard.");
  };
  this.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?
      });
    });
  };
}

then
var x = new pokedexObject();
x.charizard();
x.squirtle();

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