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
You have already learned that JavaScript variables are containers for data values. Objects are variables too. But objects can contain many values. The values are written as name:value pairs (name and value separated by a colon).
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.
An object contains properties, or key-value pairs. The desk object above has four properties. Each property has a name, which is also called a key, and a corresponding value. For instance, the key height has the value "4 feet" . Together, the key and value make up a single property.
When you copy an object b = a both variables will point to the same address. This behavior is called copy by reference value. Strictly speaking in Ruby and JavaScript everything is copied by value. When it comes to objects though, the values happen to be the memory addresses of those objects.
Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).
JavaScript objects have two types of properties: data properties and accessor properties.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With