2013-07-16 35 views
6

我模拟了Java脚本的一类,它的代码是在这里:如何通过引用JavaScript中的事件处理程序来传递变量?

function myclass() 
{ 
    this.count ; 

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

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

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

感谢您的帮助

回答

2

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

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

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

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); 
    } 
} 
4

不能增加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

+0

我测试以及和作品正好。 – adeneo

相关问题