friend.sayHello = person.sayHello;

Hello,

I will paste my code below, but I am a little confused about what the “friend.sayHello = person.sayHello” is doing. Any pointers would be great.

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

let friend = {
  name: 'Chris',
}
friend.sayHello = person.sayHello;

console.log(person.sayHello());

person.hobbies = ['Basketball', 'Coaching'];
person.hobbies = ['Basketball'];
console.log(person.hobbies);


console.log(person['name']);
console.log(person['age']);

let day = 'Tuesday';
let alarm;

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

console.log(person[alarm]);
console.log(friend.sayHello());

our person object has a method named sayHello, now we want to add the same method to our friend object, instead of re-writing the whole method, we simply assign the sayHello method of person object to friend object, given the method the same name in the process, we could also do:


let friend = {
  name: 'Chris',
}
friend.anotherName = person.sayHello;
friend.anotherName();

maybe demonstrating with a function is easier, console.log() is very long to write so we could do:

a = console.log
a("hello world")

we just created another function, assigning it an already existing function

1 Like

OK. That makes sense. I can use methods within an object, on other objects. I would assume this is practical if the method is lengthy and confusing.

Are you saying I can set a variable like “a” to be my console.log so that I dont have to type it out every time? Is this good practice in real life application?

Thanks a bunch for the quick response.

no, you can add a method from one object to another object. Then you can use the newly added method to the object to which you added, this is why i showed the function, you can create a duplicate of a function, by simply assigning it.

no, absolutely not. Its just to show how functions can be copied to a new variable

1 Like