goo*_*ons 1 javascript jquery class jquery-events
我想在触发 onclick 事件时从类中调用“成员”函数。onclick 事件本身应该绑定在类中。这就是我所拥有的:
var MyClass = function()
{
this.value = 'hello';
this.update = function()
{
console.log(this.value);
// Do some things with this.value
};
$('#button').click(this.update);
};
Run Code Online (Sandbox Code Playgroud)
浏览器在更新函数中抱怨 this.value 未定义。
在处理函数中,this指的是您点击的按钮。为了规避它,您可以存储对this局部变量的引用,然后使用它。在这种情况下最常用的变量名称是self或that。
var MyClass = function() {
var self = this;
self.value = 'hello';
self.update = function() {
console.log(self.value);
// Do some things with self.value
};
$('#button').click(self.update);
};
Run Code Online (Sandbox Code Playgroud)
或者正如其他人所提到的,您可以明确地使用MyClass.update.