简体   繁体   English

Javascript:onclick不会调用函数

[英]Javascript: onclick does not call function

When I run the following code, the alert messages shows up but this.test() does not run. 当我运行以下代码时,将显示警报消息,但this.test()无法运行。

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. this.test()将运行。

EDIT: I have added more details to my code. 编辑:我已经添加了更多细节到我的代码。

In the first example, the word "this" refers to function itself. 在第一个示例中,单词“ this”是指功能本身。 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. 但是在第二个代码中,您正在告诉代码this.test()是实际的onclick函数,这就是为什么它在此处起作用而不是在第一个函数上起作用的原因。

Your issue is related to scope. 您的问题与范围有关。 Try: 尝试:

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

this will vary depending upon where it is called from. this取决于调用它的位置。 In your first example, you are calling it from within an anonymous function and therefore the scope of this shifts to inside that function. 在你的第一个例子,你从一个匿名函数中调用它,因此范围this转移到该函数内部。 In the second example, the scope is a level higher and refers to your SomeFunction() function. 在第二个示例中,范围是更高的级别,并且引用了SomeFunction()函数。

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. 由于你的函数嵌套在另一个函数里面,你可能要重新分配this到另一个变数是访问了作用域链。 Eg 例如

function SomeFunction() {

    that = this;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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