How to add method to an object from outside
person.sayAge = function () {
return `${this.name} is ${this.age} yrs old.`;
};
console.log(person.sayAge());
Task - Create a new array and add at least two methods from outside as well as call it.
From today wherever you see something.something its the property accessing and when you see something.something() then its a method access. eg. string.length is property access while string.toUpperCase() is method access. - VIP conclusion.
But one thing is to note down. -
When we create a string like "hello", it is a primitive, not an object.
But when we try to access a property (like .length) or a method (like .toUpperCase()), JavaScript temporarily wraps the primitive inside a String object.
The global String object acts like a class, and is technically called a global constructor function.
This constructor behaves like a class and provides access to methods and properties.
const str = "hello";
console.log(str.toUpperCase());
//Behind the scene
const temp = new String("hello"); // temporary object
console.log(temp.toUpperCase()); // calls the method
temp is then discarded
Spread Operator
const person = {name: "Ram", age: 25};
const newPerson = {...person, location: "Kathmandu"};
console.log(newPerson);
Destructuring
const user = { name: "Ram", age: 25 };
const { name, age } = user;
console.log(name); // Ram
console.log(age); // 25
Map for array of objects
Tasks -