Anthony
Anthony

Reputation: 2411

In JavaScript is there a difference between referencing an object's variable name vs. using `this` when declaring new key:value pairs of the object?

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

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

Upvotes: 7

Views: 577

Answers (1)

Felix Kling
Felix Kling

Reputation: 816442

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

foo is not the name of the object it is the name of the variable.

And variables can change. Consider this:

var bar = foo;
foo = null;

Using foo would break the code code, but when using this, 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.

Upvotes: 9

Related Questions