Object.key vs thiskey

Hi guys,

I was wondering about the difference between object.key and this.key and need your help to clarify. I tried both and the results were the same.

Here is the code snippet.

1

.

const arobot = {

model: 'B-4MI',

mobile: true,

greeting() {

console.log(arobot.model);

}

};

arobot.greeting() // output : B-4MI


const arobot = {

model: 'B-4MI',

mobile: true,

greeting() {

console.log(this.model);

}

};

arobot.greeting() // output : B-4MI

In this case, we can use both arobot.model and this.model?

Hi there!

When you wish to reference a property or call a method of an object from within the scope of that same object, the this keyword guarantees that the referenced object will always be what you expect.

In the first example you provided, the greeting() method is accessing the model property of the object held in the arobot variable. Now imagine that you named the variable differently or wished to have another instance of that object in a different variable, you would have to change the hard coded reference in the greeting() method and adapt it to each case. By using this to reference the object, you won’t have this issue as it will always reference the same object, regardless of the name of variable that is holding it.