tags:

views:

638

answers:

3

Hey.

Let's say I have this:

test = function() {

 this.init = function() {
  $("#someElement").html("Hey!").mousedown(function() {
   $(this).html("Clicked");

   /* 
    Now, if I wanted it to call function "dosomething" defined in the class, how would I do that? this.dosomething() obviously doesn't work.
   */

  });
 }

 this.dosomething = function() {
  alert("Did it!");
 }

}

var _go = new test();
_go.init();
+2  A: 

Encapsulate the "dosomething" call into a javascript variable in your outer function, and reference it in your inner function.

this.init = function() {
var doSomething = this.doSomething;  
$("#someElement").html("Hey!").mousedown(function() {
   $(this).html("Clicked");

      doSomething();   

  });
 }

This creates a closure where the inner function still has a reference to the variables in the outer function.

womp
+1  A: 

You can set a context before losing the reference to your class:

test = function() {

  var context = this;

  init = function() {
    $("#someElement").html("Hey!").mousedown(function() {
      $(this).html("Clicked");
      context.dosomething();

    });
  }

  dosomething = function() {
    alert("Did it!");
  }

}
Joel Potter
Thanks!I see that user womp also edited his answer for dumbusers like me, so thank you both very much!
Yeah I had a distraction for a few minutes while adding the code example. Sucks to be me ;)
womp
A: 

Declare test as being an new function() beforehand.

test = new function() {};

test.init = function() {
    test.foo();
};

I'm sure there are other / better ways to do this but I know that works.

smack0007