Why this keyword is undefined inside my function?

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.

Challenge: Change the Prototype to a New Object

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object

Share you code here someone will help you for sure

Arrow functions have no this context, that’s one of the reasons they exist. They use the parent context instead, which in this case is global

In objects, rather than writing method: function () {, you can write method() {, they’re the same thing

Dog.prototype = {
  numLegs: 4,
  eat() {
    return "nom nom nom";
  },
  describe() {
1 Like

Thanks, Where to use arrow functions ?

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;
  }
}
1 Like

Thanks Dan i didn’t knew that.

1 Like