Can't get the difference

What’s the difference in these codes if they work same?

const name = "Nick";
const age = 21;
const print = function(){
    console.log(`Mr. ${name}  is  ${age} years old`);
};
const person = {name, age, print};
print();

and this one

const name = "Nick";
const age = 21;
const print = function(){
    console.log(`Mr. ${this.name}  is  ${this.age} years old`);
};
const person = {name, age, print};
person.print();

The first one doesn’t require const person to work at all.

You are creating an object person that references the const name / age and the function print() now as properties and a method of person

So in effect you are creating a ‘person’ for no reason.

maybe this will help…

const name = "Nick";
const age = 21;
const print = function(){
    console.log(`Mr. ${name}  is  ${age} years old`);
};

let person = {
  who: name,
  howOld: age,
  painter: print,
  printer: function(){
    console.log(`${this.who} is ${this.howOld} today`)
  }
}

print();
person.painter()
person.printer()

print() is calling const print
person.painter() is calling const print
person.printer() is calling person[printer]

if you call printer() you will get an error printer not defined because printer() is only defined on the person object.

whereas person.painter is saying person.painter = const print find const print and call it

1 Like