Adding prototype function as an event handler

Adding prototype function as an event handler

Hey guys,

I need to know how to add an event to a button. The specific issue is that I want to add an event which is a prototype function of a class. Consider the following as an example:

  1. MyTestClass = function() {
        this.firstName = "Pete";
        this.lastName = "Johnson";
       
        MyTestClass.prototype.getFirstName = function() {
            return this.firstName;
        };

        MyTestClass.prototype.getLastName = function() {
            return this.lastName;
        };
     
        MyTestClass.prototype.showFullName = function() {
            alert(this.getFirstName() + ' ' + this.getLastName());
        };

        MyTestClass.prototype.initialise = function() {
            $('#test-btn').click(this.showFullName);
        };
    }

    var testClass = new MyTestClass();

    function onFormLoad() {
        testClass.initialise();
    }



























Look at the line: $('#test-btn').click(this.showFullName);

When the button is clicked, the event will actually get triggered, but there is a scope problem because the showFullName() function will produce the following error:

"this.getFirstName is not a function" on this line: alert(this.getFirstName() + ' ' + this.getLastName());

Is there any way to get around this problem or am I forced to use inline functions as event handlers?