hey guys, during the challenges I am trying to implement es6 practice.
can you tell me how come this one isn’t working?
ty.
**Your code so far**
let dog = {
name: "Spot",
numLegs: 4,
sayLegs: () => `This dog has ${dog.numLegs} legs.`;
};
dog.sayLegs();
edit : sayLegs: () => {return This dog has ${dog.numLegs} legs.;}` seems this code passes.
is it because I use es6 template strings, so I have to add curly bracers and return? (since it makes it not a one line return)?
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36
Everything is fine with your code except that you have a semicolon at the end of the sayLegs function definition, which you don’t want since you are defining properties on an object. Get rid of that semicolon and it will pass.
You can definitely use arrow functions and single line returns in objects/classes but you need to understand the impact it has on this. Since @TheOctagon3323’s solution doesn’t rely on this then it makes no difference which function syntax you use.
The statement in that stackoverflow comment that starts “Arrow functions cannot be used to write object methods” is wrong, but they did qualify it by saying “since arrow functions close over the this of the lexically enclosing context, the this within the arrow is the one that was current where you defined the object.”, so I’ll give them credit for the explanation that narrows down what they actually intended to say. They really should have reversed these two points and said something like:
“If you need to access properties on the object itself using this then you can’t use the arrow function syntax because it will change the meaning of this and it won’t point to the object any more.”
I am still practicing my es6, Arrow function expressions - JavaScript | MDN I can’t always remember what I need or don’t but when it’s a single line you don’t need. But on other circumstances it changes.