I have a question related to JavaScript object initializer notation. I am a bit surprised that the top example works since it's referring to the name of the instance in the definition. Are the two approaches identical? I have typically used the second approach, but they seem to achieve the same thing.
var myObj =
{
Message:"Test",
someMethod:function(){
$.get("/someUrl",function(){
myObj.Message = "Returned Value";
})
}
}
var myObj =
{
Message:"Test",
someMethod:function(){
var that = this; //have to capture this in order to use it in a different context.
$.get("/someUrl",function(){
that.Message = "Returned Value";
})
}
}
I guess the top approach has advantages since you don't have to keep track of the current meaning of this
since it may change in different contexts. Are there other differences?
Edit:
Understand that the top approach is not always a recommended approach, but I guess I still see some advantages in certain cases. One such case is KnockoutJS where the binding parsing will redefine the meaning of this
in bound click handlers on the view model. More here:
http://www.appliness.com/10-things-to-know-about-knockout-js-on-day-one/.
In this case I would have to manually do some bookkeeping of the current meaning of this
I typically use the second approach, but I was just trying to fully understand the difference and why it even works :-). Definitely understand that it's only workable in a single instance scenario though.