如何通过引用 javascript 中的事件处理程序来传递变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17669026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:08:03  来源:igfitidea点击:

How to pass a variable by reference to an event handler in javascript?

javascriptjqueryjavascript-eventsevent-handling

提问by frogatto

I simulated a class in java script, It's code is here:

我在java脚本中模拟了一个类,它的代码在这里:

function myclass()
{
    this.count ;

    this.init = function(){
        $("div.mybtn").click({n:this},function(e){
            e.data.n.count++;
        });
    }

    this.getCount = function(){
        alert(this.count);
    }
}

Then I created an instance of this class and executed it's method init(),But when I click on any div.mybtnelement, It did not increment the value of this.count.
It seems the object thiswas passed to event handler by value not by reference.
How I can pass a variable to an event handler by reference?

Thanks for any help

然后我创建了这个类的一个实例并执行了它的方法init(),但是当我点击任何div.mybtn元素时,它并没有增加this.count.
似乎该对象this是通过值而不是引用传递给事件处理程序的。
如何通过引用将变量传递给事件处理程序?

谢谢你的帮助

采纳答案by Barmar

Javascript doesn't have pass-by-reference parameters. For what you want, you should use a closure variable:

Javascript 没有传递引用参数。对于你想要的,你应该使用一个闭包变量:

this.init = function(){
    var self = this;
    $("div.mybtn").click(function(){
        self.count++;
    });
}

回答by adeneo

You can't increment undefined, you have to start somewhere:

你不能 increment undefined,你必须从某个地方开始:

function myclass() {
    this.count=0;   // start counting at zero !!!

    this.init = function(){
        $("div.mybtn").on('click', {n:this},function(e){
            e.data.n.count++;
            e.data.n.getCount();
        });
    }

    this.getCount = function(){
        console.log(this.count);
    }
}

var c = new myclass();

c.init()

DEMONSTRATION

示范

回答by mohkhan

You can write a bind function and bind the context with the event handler.

您可以编写一个绑定函数并将上下文与事件处理程序绑定。

Function.prototype.bind = function(){
    var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();

    return function(){
        fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
    }
}

function myclass()
{
    this.count ;

    this.clicked = function(){
        this.count++;    
    };

    this.init = function(){
        $("div.mybtn").click(this.clicked.bind(this));
    }

    this.getCount = function(){
        alert(this.count);
    }
}