In JavaScript is there a difference between referencing a object’s variable name vs. using this when declaring new key:value pairs of the object?
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
Just considering the presented code, both will do the same. But there are some things to keep in mind:
foois not the name of the object it is the name of the variable.And variables can change. Consider this:
Using
foowould break the code code, but when usingthis,bar.bar()will still work as expected.By using
foo, you are making the function dependent on the name of variable, so whenever the variable changes, the function breaks. This is also an important aspect regarding code refactoring.