【发布时间】:2010-09-25 15:38:04
【问题描述】:
我创建的对象看起来像这样:
var myObject = {
AddChildRowEvents: function(row, p2) {
if(document.attachEvent) {
row.attachEvent('onclick', function(){this.DoSomething();});
} else {
row.addEventListener('click', function(){this.DoSomething();}, false);
}
},
DoSomething: function() {
this.SomethingElse(); //<-- Error here, object 'this' does not support this method.
}
}
问题是当我在 'DoSomething' 函数中时,'this' 并不引用 'myObject' 我做错了什么?
【问题讨论】:
-
1) 愚蠢的问题,但是你的对象有SomethingElse 方法吗? 2) 尝试在闭包中执行“function() {this.DoSomething(this);}”,并让 DoSomething 采用 0 args 或 1 arg - 看看会发生什么并发布你的结果。
-
你的评论说错误是在调用
SomethingElse,但实际上不是在调用DoSomething吗? -
闭包实际上和这个例子没有任何关系,如果
this的值不是来自这里的闭包。
标签: javascript closures