jQuery / javascript事件 – 原型事件处理程序

以下代码不起作用,因为我直觉地期望它:

function MyObject(input) { input.change(this._foo); this.X = undefined; } MyObject.prototype._foo = function() { alert("This code is never called"); // but if it did this.X = true; } var test_input = $("input#xyz"); // a random, existing input var m = MyObject(test_input); // attach handler (or try to) test_input.change(); // trigger event alert(mX); // undefined 

我希望调用_foo() (如果发生this情况, _foo()中的this变量将是MyObject的实例化。

有谁知道为什么这不起作用,以及将对象传递给事件处理程序的任何替代模式?

谢谢你的阅读。

布赖恩

正如肯尼指出你错过了new 。 您还需要确保_foo中的this引用MyObject实例
一种方法: –

 function MyObject( input ) { var _this = this; input.change( function() { // explicitly set the `this` in _foo to `_this` _this._foo.call( _this ); }); this.X = undefined; } MyObject.prototype._foo = function( event ) { alert("This is called"); // and 'this', being 'm', has X set to true this.X = true; // the textbox must be accessed by 'event.target' not 'this' if you need it } var test_input = jQuery("input#xyz"); // a random, existing input var m = new MyObject(test_input); // attach handler (or try to) test_input.change(); // trigger event alert(mX); // true 

PS你不能避免使用新的运算符! 🙂

要在Javascript中创建对象,请使用new

 var m = new MyObject(test_input); // attach handler (or try to) 

这个问题现在有点老了,但还有另一个解决方案。 您的问题就像我提到的那样,您错过了’new’,并且事件处理程序中的’this’引用将始终是触发事件的元素,而不是处理事件的对象。

由于您使用的是JQuery,因此可以通过简单的方式使其按照您的方式运行。 使用JQuery.proxy方法设置事件处理程序的上下文,以将对象用作“this”。 在您的示例中,您只需要更改该行

 input.change(this._foo); 

 input.change(jQuery.proxy( this, "_foo" )); 

如果再次遇到JQuery的这个问题,请尝试一下。