Object Oriented Programming: Make Code More Reusable with the this Keyword

Hello,

Can anyone give me an example of the “pitfall” mentioned on this challenge? It says “any code referencing the original name would need to be updated as well.”

I am not able to simulate what could go wrong. Just want to see it to understand “this” usage.

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

dog.sayLegs();

Thank you very much.

Could you provide the link the challenge or quote the whole paragraph?

Hello,

Sorry, please see below.

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword/

Suppose I want to create another animal object and to save some time I clone my existing dog object, like so:

let duck = Object.assign({}, dog);
duck.numLegs = 2;

Now I want to call the sayLegs method on duck:

duck.sayLegs() // Uh oh! It returns 4 legs because that function references original dog object!

If my sayLegs function said this.numLegs instead of dog.numLegs then I wouldn’t have needed to update it for other objects; it would automatically reference the calling object whether it’s dog or duck or something else.

EDIT: I realized I messed up in my initial response. Typing let duck = dog would literally have the new duck variable point to the old dog object because objects are copied by reference. If you actually wanted to make a separate new object based off another one you’d use something like Object.assign method.