0

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?

  • 1
    `this` changes depending on how the function is called. – evolutionxbox Apr 28 '21 at 20:10
  • 3
    Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – evolutionxbox Apr 28 '21 at 20:10
  • You're assuming there will be only one "user", but most programs use many objects of the same kind (or "class"). This is where `this` comes into a play. – georg Apr 28 '21 at 20:16
  • Learning by doing: Try storing the function in a variable (like `const greeting = user.greet;`) and calling it `greeting()`. Or passing it as a callback `setTimeout(user.greet, 100)` – Thomas Apr 28 '21 at 20:21
  • @evolutionxbox I was more concerned with the differences between the two. I sort of have an adequate understanding of how `this` works. Anyways it still helped me so thanks. – nikinbaidar Apr 29 '21 at 07:36
  • @Thomas It throws a TypeError. – nikinbaidar Apr 29 '21 at 07:42

0 Answers0