Hello, my name is undefined


#1

Pleased to meet you.

I’m doing this lesson here in which I was instructed to amend the sayHello() method to demonstrate the use of this. The sayHello() method was created earlier using arrow syntax (as per example in the lesson). I’ve just spent an hour trying to work out why I was getting undefined only to read that this doesn’t like arrow syntax!

sayHello: () => `Hello, my name is ${this.name}`

Doesn’t work.

sayHello () { 
    return `Hello, my name is ${this.name}`
  }

Does work.

I’m not sure if I’ve learnt a valuable lesson or wasted an hour of my life!

Why doesn’t this work in methods using arrow syntax?


#2

Arrow function notation does not have a context variable, this so the first example will not work.

The second example is missing the function keyword.

    sayHello: function () {
        return `Hello, my name is ${this.name}`;
    }

Actually, the second example is correct, as a method of an object. ES6 introduced the new syntax.


#3

Thanks for reply.

According to lesson 9 on ES6 methods, the working method above is the best practice for defining methods:

This syntax, which only requires the name of the method and parentheses, is best practice for defining methods.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.