Does `this` always refer to an object?

Question

Does this always refer to an object?

Answer

Yes, in JavaScript this will always refer to an object, the important part is to always know which object that is. For example:

const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet() {
    console.log(this.dietType);
  }
};

Since the method diet is a regular function, the meaning of the this keyword inside it relates to the method’s object since the context where regular functions exist dictates what they can use. Yet, if you were to do this in an empty js file:

console.log(this)

When you run the file (let’s say using node: node nameOfFile.js) on your terminal, this will be set to the global object which in that case will be the execution system (node) and you will probably see something like this on your terminal:
[obj]

If your JavaScript file was linked to an HTML page, then once it runs in the browser, the window object will become the global object, and calling the previous console.log would print the window object. The same way, setting functions as event listeners for HTML elements will make that any reference to this inside of the event listener function will relate to the HTML element it has been appended to.

------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this     ---------------------  |
|   ----------------      |      | functionInGlobal() |  |
|               |         |       ---------------------  |
|          --------------------                          |
|          | onclick property |                          |
|          --------------------                          |
|                                                        |
----------------------------------------------------------

That said, before using the keyword this always make sure you know which object it will refer to.

9 Likes

Yes this keyword always refers to the properties of an object.

3 Likes

“The this keyword references the calling object which provides access to the calling object’s properties. In the example above, the calling object is goat and by using this we’re accessing the goat object itself, and then the dietType property of goat by using property dot notation.”

I understand why we can’t access the key of object inside method , because of scope like global variables and local variables.true ?

What is calling object ?
what are calling objects properties and this is only of them ?
if we wanted to use local variable outside of objects topic i mean using variable defined in for loop {} s outside of it WE COULD use again this method or something like this .

what is the process of : that this letting us to rescue global and local scope .

1 Like

goat object isn’t global scope to .diet method here ?

like we can use variables defined in function in for loops inside that function .

3 Likes

Why we Dont use goat.dietType insted of refering keyword like this to use this.dieType.?

like when we can use console.log(goat.dietType);

5 Likes

Here we go again. What on earth am I doing wrong now?

Yours seems to be the same as mine, except I think you have an extra ‘a’ in your text, as in ‘I am a model’, where the actual text they want is ‘I am model’. I think the error is not in your code, but rather a extra bit of unwanted text string. Try removing the ‘a’ and I think it’s gonna work. I’ve been caught by this kind of thing before, they seem to want exactly the text string, and nothing extra.

6 Likes

Thank you so much! Yes, I’m on 7 now (intermediate JS) and it’s definitely been the strings all along! Haha. So now I’ve been checking my spelling and spacing in strings first before anything else.

I typically copy the required text from the instruction window on the left, since the testing checker is so nitpicky.
Even the slightest error could throw you for a loop if you’re not confident in the logic structure of your code.
I’ve had lessons return errors for missing apostrophes, the use of a double-quote instead of a single-quote, or misplaced punctuation!
Beware of capitalization while you’re at it, because the error checking is super-specific about that too.

:laughing: LOL :laughing:

All good reasons to just copy/paste, in my opinion.

3 Likes

Question regarding the .this method:

[why is dietType not defined even though it’s a property of goat] because inside the scope of the .diet() method, we don’t automatically have access to other properties of the goat object.

In simple terms…what this is saying… is that .this is a local scope? I am confused as to what the above sentence is trying to make a point of…

Also, using the goat example provided by CodeCademy,

const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet() {
    console.log(this.dietType);
  }
};

why can’t we just directly use

dietType() {
     return 'herbivore'
}

and then call the function? Wouldn’t that be simpler?

Thank you so much for your help!!

The ‘this’ keyword will allow you to access to the scope outside your function, so generally, it will allow you to access the object where you wrote your methods. :slight_smile:

Blockquote dietType() {
return ‘herbivore’
}

Because if your goat.dietType change, you’ll don’t see it in your method if you only return ‘herbivore’ without reference your object.
I know your question was asked a long time ago but it can help other people. Hope i didn’t said mistake, i’m also student. :slight_smile:

3 Likes

Moved question to new topic as it was not relevant to original question.

Link: Question about this. in JavaScript

In the 2nd exercise, can someone explain to me again why we are doing a return on the interpolation vs a console.log?

3 Likes

The object name appears to work as well as using the keyword this
const robot = {
model: ‘1E78V2’,
energyLevel: 100,
provideInfo() {
return I am ${robot.model} and my current energy level is ${robot.energyLevel}; // object name instead of this keyword
} // end of method provideInfo()
}; // end of object robot
console.log(robot.provideInfo());

// Output: ‘I am 1E78V2 and my current energy level is 100’

2 Likes

Nothing you have above is wrong. It’s just not portable, by which I mean, cloneable. What if we make this a prototype and plan to have others following the same data structure? Don’t answer, we have classes for that, but play with this for awhile off and on, and figure out how to copy the robot to a new object. It will be fun, I know. Been pulling out hairs for hours on this one. Once we have a true clone with its own independence, then we can see where this comes in handy.

On another note, this is exposed, robot is not so needs repeated polling. Under the hood, this is the preferred way to address the context object. And it is portable.

4 Likes

Thanks for reply! I can see where portability could be a problem, especially if you use this same object-method chunk of code in a second similar or cloned object (cut and paste because you have more than one robot) and/or rename the object something other than ‘robot’ for code clarity reasons (e.g., robot’ vs. robotAlpha, robotBeta, …). By using robot.model versus this.model, all references will be dependent on the original object name ‘robot’ where as if you use the keyword this (i.e., this.model) the method will adapt to whatever new object name is provided (i.e., const robotAlpha { … provideInfo() { … this.model …}. Also, if the object contained many methods, using robot.model (vs. this.mode) each method will require much time consuming editing/debugging for each object name change (e.g., robotAlpha, robotBeta, RobotCharlie, …). There may be more to your response that I don’t understand yet, but will probably make sense once I learn or experience it. Best Regards, Bear . . .

6 Likes

@mtf, does the call bring the method/object into the scope of where it is called? In the example, global scope? This would make the method dietType() blind to anything else but global scope? ‘this’ gives a reference outside dietType() and up one level in scope to reveal what is available in goat or another clone’s scope?

2 Likes

The method is in object context so not really global, although the object might be. We can only call the method on the object. Nothing changes with respect to scope.

Inside the method is a new scope. However, this is bound to goat, in outer scope from the method. We refer to it anytime we wish to access other properties or methods from within a method.

Scope is not static unless we’re dealing with global scope. In all other cases it is created when a function or method is invoked, which gives us a local scope. At termination of the function, the scope and all its variable contents are destroyed.

2 Likes

Thanks. Good to hear some more on this. I also read about this and bind in the MDN. Some of that was helpful, like your reply. I think I have a pretty good handle on ‘this’, but I feel I will need more practice to open my mind to all the possibilities. ** I realize in my weird graphic the yellow question in the goat kennel should read “where is the diet type property” not “where is goat”

1 Like

Open your mind to what the language promises, separate from possibilities. We’re not playing a game of chance, only capitalizing on language and OS resources to achieve our goal.

4 Likes