Javascript Closures and 'this'
closures, javascript
Solution
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);
}
},
When the function is called, it has access to the variable theOBj which was in scope when the function was defined.
Problem
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. } } ``` The problem is that when I am inside the 'DoSomething' function, 'this' does not refer to 'myObject' what am I doing wrong?