Name is undefined


#1

I have followed the directions of the tutorial as far as I can tell and according to the tutorial my name should print to the screen however its printing out as undefined. I’m not sure why. the “this” word should make it print properly should it not?

let person = {
name: ‘Erick’,
age: 39,
weekendAlarm: ‘No alarm needed’,
weekAlarm: ‘Alarm set to 7AM’,

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

sayGoodbye() {
return ‘Goodbye!’;
},
};

let friend = {
name: ‘Don’
};

friend.sayHello = person.sayHello;

person[‘hobbies’] = [‘Coding’, ‘Trading’, ‘Shooting’];

person.hobbies = [‘coding’];

console.log(person[‘hobbies’]);

let day = ‘Sunday’;
let alarm;

if(day === ‘Saturday’ || day === ‘Sunday’) {
alarm = ‘weekendAlarm’;
} else {
alarm = ‘weekAlarm’;
}

console.log(person[‘name’]);
console.log(person[‘age’]);
console.log(person[alarm]);
console.log(person.sayGoodbye());
console.log(friend.sayHello());


#3

Arrow functions do not have a context object, so no, this. Use standard form,

 sayHello () {

},

The this keyword


#4

Thank you. This was not explained very well in the tutorial.


#5

Yeah, I couldn’t find where it is explained, either, but now you know.

Extra study:

function Person(name) {
    this.name = name;
}

The this keyword is a property of a function object.

person = {
    name: "Wee Gillis",
    age: 19
};

The above object has no this property, nor does it have a prototype object, other than the Object.prototype of its parent constructor, Object. The Person object constructor above does have a prototype. Object constructors are extended by adding methods to the prototype.

Person.prototype.sayHello = function () {
    return `Hello, my name is ${this.nam}.`;
};

We cannot extend an object the way we can its constructor. That is why the methods are written directly to the object.

person = {
    name: "Wee Gillis",
    age: 19,
    sayHello {} {
        return  `Hello, my name is ${this.name} and I am ${this.age} years old.`;
    }
};

An object inherits the scope in which it is declared, but the methods inside it have their own scope. The this property is the bridge out of that scope to the object context, itself. The methods cannot see name and age but they can access this which in turn is bound to the two properties.

Don’t let this take you away from your studies but do follow up with it when it comes time to review.

Arrow Functions


#6

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