Is there any difference between (setting a property value) with :
var obj = {
getData: function ()
{
this.age = 34 //notice this
}
}
obj.getData();
alert(obj.age) //34
vs
var obj = {
getData: function ()
{
obj.age = 34 //notice obj
}
}
obj.getData();
alert(obj.age) //34
when should I use each ?
The former is (IMHO) strongly preferred, although both “work” in these limited circumstances.
Wherever possible, an object should never refer to itself by the name it’s given in its declaration.
Using
thisensures that if the object is assigned another alias, andobjre-used, that the object still correctly refers to itself. Likewise if you decide to renameobj– you only have to change it once.