Does `this` always refer to an object?

I wrote it like this

5a134ca6676330384dda3d825ceea69a

My energyLevel is underneat method, I think thats how the exercise want you to write. For me this was the correct way,

I think this is the best explanation I ever saw. Thanks and congrats!

So; when a method is defined inside an Object the properties can’t be accessed right away as the scope is limited; right? Only using the “this” keyword → that refers to the original Object inside which this method is defined will let you access it; right?
Is this the reason why you say “at the termination of the function; scope and variable contents are destroyed” ?

Try giving this thread a read…

What is the 'Execution Context' in JavaScript exactly? - Stack Overflow

Isn’t console.log(goat.dietType); clearer than console.log(this.dietType);

That is what ‘this’ is doing right? This seems like it could lead to more errors and the possibility of it referencing a different object than what you want? Why use This at all? or are there more complex objects where it makes sense?

Not complex, just many of the same makeup. When we create objects as literals, then there is just the one. What if there are a dozen, or 100, or more, each with the same properties and methods, only unique property values? We cannot hardcode a name into code if we want it to be reusable.

In a short while you will learn about custom objects created from a sort of blueprint that ensures objects of one type, or class, have the same properties and methods. The three custom creation methods are,

  1. Factory functions
  2. Constructor functions
  3. Class definitions.

When you get into these, this will carry more importance and be easier to appreciate at face value.

2 Likes

when calling an object property inside the object, in place of this you could just use the objects name obj.key at least it worked when I tried it so why bother with this when there is such a high margin you could mess things up

We have a program that contains data objects for each of the 366 (possible) days of the year. Each object has the same properties and methods.

Think about this, are we going to write 366 separate object literals with the name embedded (hardcoded) in each one?

this comes to the rescue, as does the custom object, which will be covered in the unit on Class constructors.


Future study

class Day {
  constructor (num, date) {
    this._num = num;
    this._date = new Date(date);
  }
  get date () {
    return this._date;
  }
}
 > d = new Day(1, '2022-01-01T00:00:00')
 > d.date
<- Sat Jan 01 2022 00:00:00 GMT-0700 (Mountain Standard Time)
1 Like

I tried to do mine this way (with string concatenation) and it threw SyntaxError

const robot = {
model: ‘1E78V2’,
energyLevel: 100,
provideInfo(){
return (“I am " + this.model +” and my current energy level is " + this.energyLevel.)
}
};

Does it mean that this only works with String Interpolation and not string concatenation?

The syntax error might be the unquoted full stop at the end.

The context variable, this is a property of function and so long as there are no syntax errors can be applied in any type of string construction.

Couple things:

  • return values do not need to be in parens.
  • Only standard quotes are recognized by the interpreter.

So,

return "I am " + this.model + " and my current energy level is " + this.energyLevel + "."

or,

return `I am ${this.model} and my current energy level is ${this.energyLevel}.`

will both work as expected.

2 Likes

The both worked. Thanks @mtf

1 Like

What is wrong in this code? Not working in this topic in JS!

const robot = {
model: ‘1E78V2’,
energyLevel: 100,
provideInfo: () => {
return I am ${this.model} and my current energy level is ${this.energyLevel}.;
}
};

console.log(robot.provideInfo());

Do “self” in Python’s OOP and “this” in Java Script have the same purpose?

Yes, except with one difference: In JavaScript, ‘this’ is a defined property of the function object; whereas, in Python, self is just a variable. We can substitute in any name we wish and it will still work the same way.

Thanks for this clarification.

1 Like

I wrote this code:
const goat = {
dietType: ‘herbivore’,
makeSound() {
console.log(‘baaa’);
},
diet() {
console.log(this.dietType);
}
};
goat.diet();

It returned :
Output: herbivore

I wrote this code:
const goat = {
dietType: ‘herbivore’,
makeSound() {
console.log(‘baaa’);
},
diet() {
console.log(goat.dietType);
}
};
goat.diet();

It returned :
Output: herbivore

I used “this.dietType” and “goat.dietType” . Both worked same. So, what is the purpose of “this” method? Isn’t “this” an extra unecessary method?