I am fairly new in JavaScript and have been learning JS objects.
An object is basically a collection key:value pairs and the value to a key can be a function.
Now, to access some other key within the same object from a function this
keyword is used.
For example,
let user = {
name : "John",
greet : function () {
alert(`hello ${this.name}`)
}
};
So if I go on and run user.greet()
the output is "hello john".
But if i keep everything in the above code same, except replace the this
key word with the objectName, like so:
let user = {
name : "John",
greet : function () {
alert(`hello ${user.name}`)
}
};
The code still produces the same output.
So my question is what exactly is the advantage of using this
instead of accessing the property with the object name itself ? And what exactly is the difference between these two?