简体   繁体   中英

Javascript: 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.

In the first example, the word "this" refers to function itself. So the function test would be outside its scope.

But on the second one you are telling the code that this.test() is the actual onclick function, that is why it's working there and not on the first one.

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. Eg

function SomeFunction() {

    that = this;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM