Learn JavaScript: Objects, The this Keyword II


#1

Hello, i din’t get this:
If we call myObj.sayHello(), our method will return 'Miti says hello!'. this in the example above is called inside the myObj object, which limits the scope to the properties inside of myObj.

Let’s change that by switching the object calling this:

let yourObj = {
  name: 'Timer'
};

yourObj.sayHello = myObj.sayHello;
// Sets the sayHello method on yourObj to be the sayHello method on yourObj

If you call yourObj.sayHello(), it will return 'Timer says hello!'. this in the example above is called inside the yourObj object, which limits the scope to the properties inside of yourObj.

My code is this:

let person = {
  name: 'Tyron',
  age: 40,
  weekendAlarm: 'No alarms needed',
  weekAlarm: 'Alarm set to 7AM',
  sayHello() {
    return `Hello, my name is ${this.name}`;
  },
  sayGoodbye() {
    return 'Goodbye!';
  }
};
let friend = {
name: 'Elvin', 
  }

friend.sayHello = person.sayHello;

console.log(person.sayHello());

why do i send friend.sayhello = person.sayHello; ma i creating the method say hello in friend?


#2

yes, you seem to understand fine. We have a sayHello method in person object. Now we want to add the same method to friend object, instead of writing the method again, we are lazy and simply add the existing method to a different object


#3

so if i console the method again, it would exist? let me try


#4

yep, you should be able to call the method again but this time on friend


#6