In JavaScript, there is a difference between referring to an object variable name versus using `this` when declaring new keys: a pair of object values?

In JavaScript, there is a difference between referencing an object variable name and using this when declaring new keys: a pair of object values?

  var foo = { bar: function() { foo.qux = 'value'; } }; alert(foo.qux); // undefined foo.bar(); alert(foo.qux); // 'value' var foo = { bar: function() { this.qux = 'value'; } }; alert(foo.qux); // undefined foo.bar(); alert(foo.qux); // value 

Also: http://jsbin.com/emayub/9/edit

+7
source share
1 answer

Given the code presented, both will do the same. But there are some things to keep in mind:

foo not an object name , it is a variable name .

And variables can change. Consider this:

 var bar = foo; foo = null; 

Using foo will break the code, but when using this , bar.bar() will work as expected.

Using foo , you make the function dependent on the variable name, so whenever the variable changes, the function is interrupted. This is also an important aspect of code refactoring.

+10
source

All Articles