我正在尝试这样做:
var foo = new Foo();
foo.setEvents( foo );
foo代码:
function Foo()
{
this.id = getId(); //this works successfully, each instance of foo gets
//assigned a new auto incrementing id e.g 1, 2, 3, etc
this.setEvents = function( that )
{
$("#myButton").click( that.bar );
}
this.bar = function()
{
alert(this.id);
}
}
每当我运行此代码并单击我的按钮时,我会收到一条警告“未定义”
如何在触发事件时保留我想要运行其方法的对象的状态?
答案 0 :(得分:1)
这指的是jQuerys范围内不同的东西......
function Foo()
{
obj=this;
this.id = 1; //this works successfully, each instance of foo gets
//assigned a new auto incrementing id e.g 1, 2, 3, etc
this.setEvents = function( that )
{
$("#myButton").click( that.bar );
}
this.bar = function()
{
console.log(obj)
}
}
var foo = new Foo();
foo.setEvents( foo );
答案 1 :(得分:1)