1

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();

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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!");
  }

}

2 Comments

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 ;)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.