0

I don't know why I get an error "this.getName is not a function" when I use arrow function for the object. When I use normal function, the output is good.

Object with normal function. All good.

 var person = {
        name: 'Juan',
        lastname : 'Rodríguez',

        getName: function() {
            return this.name;
        },

        getLastname: function() {
            return this.lastname;
        },

        fullname:function () {
          return this.getName() + " " + this.getLastname()  
        }
    }

    console.log(person.fullname());  // good output Juan Rodríguez

However with arrow function () => , I get error as "this.getName is not a function"

 var person = {
        name: 'Juan',
        lastname : 'Rodríguez',

        getName: () => {
            return this.name;
        },

        getLastname: () => {
            return this.lastname;
        },

        fullname: () => {
          return this.getName() + " " + this.getLastname()  
        }
    }

    console.log(person.fullname()); // bad output this.getName is not a function

Any solution so that I do not get the error? If I want to use arrow functions?

Chen Hanhan
  • 1,549
  • 6
  • 15
  • 20
  • 2
    With an arrow function, the current `this` context gets bound, in that case, it would be the outer scope of the object (so global or `undefined`) – Icepickle Nov 21 '18 at 08:04
  • [When (and why) you should use ES6 arrow functions — and when you shouldn’t](https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26) – yunzen Nov 21 '18 at 08:23
  • what should I do so that I do not get an error, if I want to use arrow functions? – Chen Hanhan Nov 21 '18 at 09:51
  • 1
    @ChenHanhan — That's like asking how to get nails in cleanly if you want to use a screwdriver instead of a hammer. Stop wanting that. Use the right tool for the job. – Quentin Nov 21 '18 at 10:08

0 Answers0