What are the ways of making objects in JavaScript?
Using Object Literal.
const o = {
name: "Mark",
greeting() {
return `Hi, I'm ${this.name}`;
}
};
o.greeting(); //returns "Hi, I'm Mark"
Using Constructor Functions.
function Person(name) {
this.name = name;
}
Person.prototype.greeting = function () {
return `Hi, I'm ${this.name}`;
}
const mark = new Person("Mark");
mark.greeting(); //returns "Hi, I'm Mark"
Using Object.create method.
const n = {
greeting() {
return `Hi, I'm ${this.name}`;
}
};
const o = Object.create(n); // sets the prototype of "o" to be "n"
o.name = "Mark";
console.log(o.greeting()); // logs "Hi, I'm Mark"