I passed but, i still don't understand what this is :Make Code More Reusable with the this Keyword

Tell us what’s happening:
I tried to understand what the lesson was about but its very vague.

this is a deep topic, and the above example is only one way to use it.
Okay but that doesn’t add anything
In the current context, this refers to the object that the method is associated with: duck .
what kind of method?
.If the object’s name is changed to mallard , it is not necessary to find all the references to duck in the code. It makes the code reusable and easier to read.
But how does it do that? also, where we not just talking to something associated to a method? where does the object suddenly come from?

Your code so far
[spoiler]


let dog = {
name: "Spot",
numLegs: 4,
sayLegs: function() {return "This dog has " + this.numLegs + " legs.";}
};

dog.sayLegs();

[/spoiler]

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Make Code More Reusable with the this Keyword

Link to the challenge:

I think this refers to sayName in the duck:

  sayName: function() {return "The name of this duck is " + this.name + ".";}

If the object’s name is changed to mallard , it is not necessary to find all the references to duck in the code.

Original, supposed to be renamed to “mallard”:

let duck = { 
  name: "Aflac",
  numLegs: 2,
  sayName: function() {return "The name of this duck is " + this.name + ".";}
};

The way I understand it is, with the this keyword in place, all that needs to change is :

// before:
let duck = { 
// after:
let mallard = {

If the this is not used, the following change needs to be made as well:

// before:   
sayName: function() {return "The name of this duck is " + this.name + ".";}
// after:
sayName: function() {return "The name of this duck is " + mallard.name + ".";}

In the given example it is only one additional word, but if you have many, it could add up …

1 Like

where does the object suddenly come from?

It doesn’t suddenly come from anywhere, it’s the thing that you’ve written (or is described in the lesson as written)

dog.sayLegs()
 ↑
this, it's the thing to the left of the dot

So when you call the function, this refers to the context it was called. The context is, it’s attached to an object called dog. So dog is the context. So this.numLegs is dog.numLegs

1 Like