Jump to content

Scope Problem access 'this' - 'game'


jjwallace
 Share

Recommended Posts

var self = this.game;
        $(".audiotoggle").click(function(self) {
            if (MyApp.gameMuted === false) {
                MyApp.gameMuted = true;
                self.sound.mute = true;
               // self.audioToggle();
            } else {
                MyApp.gameMuted = false;
                self.sound.mute = false;
                //self.audioToggle();
            }
        });

Uncaught TypeError: Cannot set property 'mute' of undefined

Link to comment
Share on other sites

I think what you want line 2 to say is

$(".audiotoggle").click(function() {

Otherwise when the click occurs its going to create a variable called self in the scope of the click event handler. The click event is going to pass in the event object (the click event) and that doesn't have a property object of sound.

Omitting that will cause that click event handler to pull in the self from outside its internal scope. Do a console.log on self from inside the function and I think you'll see what I'm talking about.

Link to comment
Share on other sites

If you followed Eric's advice then your problem is with what `this.game` is referencing at the top of your snippet and has nothing to do with scope. By using closure the `self` variable is accessible from the interior function, effectively circumventing scope altogether.

JS event listeners attached to DOM elements fire in the scope of the caller, i.e. `this` will reference the element that the user interacted with, jQuery complicates this by mutating scope. In either case you either use closure to pass in an external variable (self) or you bind the function so that `this` references whatever you want it to.

The alternative is to take the approach that `this` is evil and should never be used, probably best you don't go there just yet, you need to get a firm handle on how JS handles scope before ditching it!

Add a `console.log( this.game )` before your top line, if it logs the game object you are expecting then the following will work:

console.log( this.game )
var self = this.game
$( '.audioToggle' ).click( function() {
  console.log( self )
})

From what you are saying that first console log will not log what you think, infact, it will probably throw an error.

Actually, there is another alternative to what is happening, from some of your other posts, you use globals and have leaks all over the place, is it possible that by the time someone clicks the audio button that you have overwritten `self` somewhere else in your code? The console log inside the click handler in the snippet above should confirm this.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...