Creating an object in JavaScript
June 29, 2021
Object literal syntax
If we want to create an object called fruit
, we can use the object literal syntax.
const fruit = {
name: "🍎 apple",
buy: function () {
console.log("By a fruit");
},
};
If we want to create a new object, we can do so by duplicating the existing code:
const anotherFruit = {
name: "🍏 apple",
buy: function () {
console.log("By a fruit");
},
};
Factory Function
In order to avoid code duplication we can refactor the code by using a Factory Function.
A Factory Function is a function that returns an object. A Factory Function is not a class or a constructor function.
function fruit(name) {
return {
name,
buy: function () {
console.log("buy a fruit");
},
};
}
const firstFruit = fruit("🍎 apple");
firstFruit; // {name: "🍎 apple", buy: ƒ}
firstFruit.buy();
Constructor Function
Another way to create an object is by using a Constructor Function. The naming function for a Constructor Function is that the function name starts with an uppercase letter.
Notes:
The new
operator is doing the following:
- It creates an empty object;
- It set
this
to point to that object in order to set the properties of the object; - It returns that object from the Fruit function.
- By default,
this
points to the global object which is the window object, but by using thenew
operator it references the object that is stored in memory.
function Fruit(name) {
console.log("this is", this);
this.name = name;
this.buy = function () {
console.log("buy a fruit");
};
}
const fruitOne = new Fruit("🍎 apple"); // 'this is' Fruit {}
const fruitTwo = Fruit("🍏 apple"); // 'this is' Window {window: Window, self: Window, document: document, name: "", location: Location, …}
Important notes
Every object in JavaScript has a property called constructor
that references the function that was used to create that object.
When using the object literal syntax to create an object the constructor it references the built-in constructor function.
fruit.constructor; // ƒ Object() { [native code] }
let obj1 = {};
obj1.constructor; // ƒ Object() { [native code] }
// Internally JavaScript engine translate the code to this:
let obj1 = new Object();
When the object was created using a Factory Function, the constructor references the the built-in constructor function because the Factory Function it returns an object.
function fruit(name) {
return {
name,
buy: function () {
console.log("buy a fruit");
},
};
}
const firstFruit = fruit("🍎 apple");
firstFruit.constructor; // ƒ Object() { [native code] }
When the object was created using a Constructor Function, the constructor references the function that was used to create it.
function Fruit(name) {
this.name = name;
this.buy = function () {
console.log("buy a fruit");
};
}
const fruitOne = new Fruit("🍎 apple");
fruitOne.constructor;
// ƒ Fruit(name) {
// this.name = name;
// this.buy = function() {
// console.log('buy a fruit');
// }
// }