Learning javascript Objects: TypeError: Cannot read property 'name' of undefined


#1

Hi, I’m doing the Learn Javascript introduction course, and I’m at the section on Objects. I have this code:

let person = {
  name: 'Tyron',
  sayHello: () => {
    return `Hello, my name is ${this.name}`;
  }
};

console.log(person.sayHello());

And it’s giving the below error.
Why can it not find name using the this.name notation?

Oops! The test returned an error. Maybe you have a syntax error, or a typo. Hide error.
/home/ccuser/workspace/learn-javascript-objects-objects/main.js:6
return 'Hello, my name is ’ + undefined.name;
^

TypeError: Cannot read property ‘name’ of undefined
at Object.sayHello (main.js:4:33)
at main.js:8:20
at Object. (main.js:33:1)
at Module._compile (module.js:571:32)
at loader (/home/ccuser/node_modules/babel-register/lib/node.js:158:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/ccuser/node_modules/babel-register/lib/node.js:168:7)
at Module.load (module.js:488:32)
at Object.load (/home/ccuser/node_modules/rewire/lib/moduleEnv.js:20:18)
at internalRewire (/home/ccuser/node_modules/rewire/lib/rewire.js:57:15)
at rewire (/home/ccuser/node_modules/rewire/lib/index.js:11:12)
at Object. (test.js:3:15)
at Module._compile (module.js:571:32)
at loader (/home/ccuser/node_modules/babel-register/lib/node.js:158:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/ccuser/node_modules/babel-register/lib/node.js:168:7)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at /home/ccuser/node_modules/mocha/lib/mocha.js:220:27
at Array.forEach (native)
at Mocha.loadFiles (/home/ccuser/node_modules/mocha/lib/mocha.js:217:14)
at Mocha.run (/home/ccuser/node_modules/mocha/lib/mocha.js:469:10)
at Object. (/home/ccuser/node_modules/mocha/bin/_mocha:404:18)
at Module._compile (module.js:571:32)
at Object.Module._extensions…js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3


#2

please see this docs:

you have to a valid way to write a method (as described in the docs), otherwise this will refer to the window object, not the current person object

ideally, use es6.