0

Possible Duplicate:
“this” keyword in event methods when using JavaScript prototype object

I have created a class called MyClass in Javascript and bound the onclick event to a button on the page. When the onclick event fires I want to call another member function but it gives me undefined error. please help.

//MyClass constructor
MyClass = function() {

//Find search button
this.ctrlSearchButton = $("#btnSearch");

//Attach onclick event to search button
this.ctrlSearchButton.click(this.onSearchButtonClick);
};

MyClass.prototype.onSearchButtonClick = function () {
    DoSearch();// ERROR : Object Expected
};

MyClass.prototype.DoSearch = function () {
    alert("search called");
};
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
amit
  • 251
  • 5
  • 8

1 Answers1

0
MyClass = function() {
    var self = this;
    this.onSearchButtonClick = function () {
        self.DoSearch();// ERROR : Object Expected
    };
   this.DoSearch = function () {
       alert("search called");
    };
  ....
}
Betty
  • 9,109
  • 2
  • 34
  • 48
  • actually you could probably just move the MyClass.prototype declarations into the MyClass = function() method, so you can access this without needing the self declaration – Betty Oct 01 '12 at 22:49