1

I want to use JQuery in a Javascript program I'm working on but I ran into some issues with scope. How do I call myfunction2 from myfunction1 in this psuedo-code? (assume that a new MyConstructor object has been created somewhere and that myfunction1() has been called)

function MyConstructor(){...}

MyConstructor.prototype.myfunction1 = function(param) {
   $('#some_element').click(function(){
    this.myfunction2('clicked!'); //this doesn't work
  });
}

MyConstructor.prototype.myfunction2 = function(param) {

}

1 Answer 1

2

myfunction2 can be called with this.myfunction2() when in any function of MyConstructor.

In your case you are trying to call myfunction2 inside another function that has a different meaning for this. To access myfunction2 you can create a variable for either this or this.myfunction2 that is in closure scope that extends to the function parameter of click

var self = this; 
$('#some_element').click(function(){
   self.myfunction2('clicked!');
});

or

var myfunction2 = this.myfunction2; 
$('#some_element').click(function(){
   myfunction2('clicked!');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.