Hi, I’m learning JS by following MDN’s Learn web deelopment. In Classes in JavaScript - Learn web development | MDN, it introduces construction function using the code
function createNewPerson(name) {
const obj = {};
obj.name = name;
obj.greeting = function() {
alert('Hi! I\'m ' + obj.name + '.');
};
return obj;
}
and the conclusion
This works well enough, but it is a bit long-winded; if we know we want to create an object, why do we need to explicitly create a new empty object and return it?
but this is not enough to introduce construction function to me, since what about returning the whole object at a time? it works as well according to my test, it is not long
function createNewPerson2(name) {
return {
name: name,
greeting: function () {
alert(`Hi! I'm ${this.name}.`);
}
};
}
const p1 = createNewPerson2("akk");
console.log(p1.name);
p1.greeting();