Tell us what’s happening:
When i use describe:function() syntax it works fine.
When to use arrow function and when not to any cheatsheet ??How do i set this to my Dog instance ? Do i have to use call(), apply() ?
Your code so far
function Dog(name) {
this.name = name;
}
Dog.prototype = {
// Add your code below this line
numLegs:4,
eat:()=>" nom nom nom ",
describe:()=>{
console.log(`My name is and ${this}`);
}
}
let d1 = new Dog("bRUN");
console.log(d1.describe());
//My name is and undefined
undefined
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.
Anywhere you want where the above isn’t an issue. It helps to understand how this works in JS in some situations such as this challenge before you try to use them
Most common reason I guess is that makes it easier to write functions that take functions as an argument. They extremely common in JS, so arrow functions are also extreme common.
setTimeout(() => /* do something */, 1000);
[1,2,3,4].map((num) => num * 10);
element.addEventListener('click', (event) => {
/* do something */
});
A load of other uses, for example avoiding needing to bind when using the new class fields syntax (following isn’t an example of needing binding, but I can’t think of a good example outside of React, which I think will be a bit beyond you at the minute)
class Dog {
numLegs = 4;
eat = () => "nom nom nom";
describe = () => `My name is ${this.name}`;
constructor (name) {
this.name = name;
}
}