Table of contents
In JavaScript, there are two ways of creating objects, namely
Factory functions, and
Constructor functions
const firstChild = {
age: 2,
weight: 11,
speak() {
console.log('Ma!')
}
}
const secondChild = {
age: 3,
weight: 15,
speak() {
console.log('Papa!')
}
}
As you can see, there's duplicate code in the above program which we must avoid at all cost. Let's solve this problem using factory function first and then using constructor function.
Factory function
function createChild(age, weight, firstWord) {
return {
age,
weight,
speak() {
console.log(`${firstWord}!`);
},
};
}
const firstChild = createChild(2, 11, 'Ma');
const secondChild = createChild(3, 15, 'Papa');
Constructor function
function Child(age, weight, firstWord) {
this.age = age;
this.weight = weight;
this.speak = function () {
console.log(`${firstWord}!`);
};
}
const firstChild = new Child(2, 11, 'Ma');
const secondChild = new Child(3, 15, 'Papa');
new
does three things:
create an empty object
set
this
to point to the empty objectreturn the object from the function
this
is a reference to the object that is executing this piece of code. Note that by default, this
points to the global object.
In the context of a browser, the global object is the window
object. Whereas, in Node.js environment, the global object is the global
object.