If you read the topic and you had a similar problem in the past, you will immediately understand what this article is all about. If not it just may be an interesting learning.
You maybe like anonymous functions and the beauty of using forEach on JS Arrays. If you do you may come to a point where you want to call other functions of the same object or even the same function recursively but stumble over the problem. Lets assume this code:
var something = {
doThis : function (data) {
if (!data) {
return;
}
data.forEach(function (d) {
doThat(d);
})
},
doThat : function (object) {
// TODO do that with object
console.log("That is: {0}", object);
}
}
// just delegate this data array to "something"
something.doThis(["Foo", "Bar", "Foo Bar"])
Looks good on first glance but will fail with an error like this:

Why is that? Well the reason is that the function doThat was called without any object and its not available in the root scope. So lets try to fix this part:
var something = {
doThis : function (data) {
if (!data) {
return;
}
data.forEach(function (d) {
// fix 1
this.doThat(d);
})
},
doThat : function (object) {
// TODO do that with object
console.log("That is: {0}", object);
}
}
// just delegate this data array to "something"
something.doThis(["Foo", "Bar", "Foo Bar"])
Strangely this fails now again with:

Why is that? Well the problem is that "this" is not the "something" object but the anonymous function! <?WORD FLAGGED?>!
If you search the internet you will find some solutions, I found this one. Following the advice we end up with:
var something = {
doThis : function (data) {
if (!data) {
return;
}
// fix 2
var that = this;
data.forEach(function (d) {
// fix 2
that.doThat(d);
})
},
doThat : function (object) {
// TODO do that with object
console.log("That is: {0}", object);
}
}
// just delegate this data array to "something"
something.doThis(["Foo", "Bar", "Foo Bar"])
Leading to output:
That is: Foo
That is: Bar
That is: Foo Bar
Happy Scripting
Jan