Search code examples
javascriptdom-events

onclick does not call function


When I run the following code, the alert messages shows up but this.test() does not run:

function SomeFunction() {
    document.onclick = function(e) {
        alert("Hi");
        this.test();
    };
}

SomeFunction.prototype.test = function (){
    ...
}

However when I try this:

function SomeFunction() {
    document.onclick = this.test();
}

SomeFunction.prototype.test = function (){
    ...
}

this.test() will run.

EDIT: I have added more details to my code.


Solution

  • Your issue is related to scope. Try:

    document.onclick = function(e) {
        alert("Hi");
        test();
    };
    

    this will vary depending upon where it is called from. In your first example, you are calling it from within an anonymous function and therefore the scope of this shifts to inside that function. In the second example, the scope is a level higher and refers to your SomeFunction() function.

    Since your function is nested inside another function, you may want to reassign this to a another variable that is accessible up the scope chain. E.g.

    function SomeFunction() {
    
        that = this;
    
        document.onclick = function(e) {
            alert("Hi");
            that.test();
        };
    }