Javascript闭包和'this' [英] Javascript Closures and 'this'
本文介绍了Javascript闭包和'this'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题,我创建的对象看起来像这样:
I have a problem with an object I have created that looks something like this:
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 '
The problem is that when I am inside the 'DoSomething' function, 'this' does not refer to 'myObject' what am I doing wrong?
推荐答案
当函数被调用时, this指的是行。如果你想有对象,你可以这样做:
]
WHen the function is called, "this" refers to row. If you want to have the object, you can do it something like 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);
}
},
当函数被调用时,定义函数时范围内的变量obj。
When the function is called, it has access to the variable theOBj which was in scope when the function was defined.
这篇关于Javascript闭包和'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文