3 回答
TA贡献1906条经验 获得超3个赞
当函数被调用时,“this”指的是行。如果你想拥有这个对象,你可以这样做:]
AddChildRowEvents: function(row, p2) {
var theObj = this;
if(document.attachEvent) {
row.attachEvent('onclick', function(){theObj.DoSomething();});
} else {
row.addEventListener('click', function(){theObj.DoSomething();}, false);
}
},
调用该函数时,它可以访问定义函数时在范围内的变量theobj。
TA贡献1880条经验 获得超4个赞
this总是指内部函数,如果你有嵌套函数,你必须创建另一个变量并指向它this。
var myObject = {
AddChildRowEvents: function(row, p2) {
var that = this;
if(document.attachEvent) {
row.attachEvent('onclick', function(){that.DoSomething();});
} else {
row.addEventListener('click', function(){that.DoSomething();}, false);
}
}
}
TA贡献2021条经验 获得超8个赞
这是闭包的常见问题。要解决它尝试这样的事情:
var myObject = {
AddChildRowEvents: function(row, p2) {
var self = this;
if(document.attachEvent) {
row.attachEvent('onclick', function(){this.DoSomething(self);});
} else {
row.addEventListener('click', function(){this.DoSomething(self);}, false);
}
},
DoSomething: function(self) {
self.SomethingElse();
}
}
添加回答
举报