To add a few examples:
dog = {
name: "Spot",
numLegs: 4,
sayLegs: () => `This dog has ${this.numLegs} legs.`,
};
dog.sayLegs();
"This dog has undefined legs."
Unlike functions defined with the function
syntax, arrow functions do not have their own this
(this is one of the reasons they exist). this
is the context in which you execute the function. Which, if I run this in the browser, is the object window
. So when you run dog.sayLegs()
, this
is undefined
: window.numLegs
is not a thing that exists.
dog = {
name: "Spot",
numLegs: 4,
sayLegs: () => `This dog has ${dog.numLegs} legs.`,
};
dog.sayLegs();
"This dog has 4 legs."
When I run this, sayLegs
looks for dog.numLegs
: there’s an object that has been assigned to the name dog
, and that object has the property numLegs
.
This often isn’t quite what you want: maybe you want to create lots of dogs, and they’ve all got different numbers of legs, and maybe you have a function that creates those “dog” objects somewhere else in the program, or whatever. You’re not going to want write out
dog1 = { name: "Spot", numLegs: 4, sayLegs: () => `This dog has ${dog1.numLegs} legs.` };
dog2 = { name: "Mutant", numLegs: 27, sayLegs: () => `This dog has ${dog2.numLegs} legs.` };
dog3 = { name: "Tripod", numLegs: 3, sayLegs: () => `This dog has ${dog3.numLegs} legs.` };
Every time. What you want is that sayLegs
just returns whatever the number of legs is on that specific object. So you need the function to have its own this
: at that point, can do:
dog = {
name: "Spot",
numLegs: 4,
sayLegs: function () {
return `This dog has ${this.numLegs} legs.`
},
};