Three Approaches to Creating Custom Objects in JavaScript
Methods for Creating Custom Objects in JavaScript
JavaScript supports defining user-defined objects alongside its built-in global objects and utility methods. There are three standard patterns for creating custom objects in vanilla JS, outlined below with implementation examples.
1. Enstantiate with the built-in Object constructor
This pattern directly uses the native Object constructor to create a blank object instance, with properties and methods assigned after initialization.
// Initialize empty object instance
const userProfile = new Object();
// Assign properties to the object
userProfile.userName = "Li Meiying";
userProfile.userAge = 28;
userProfile.gender = "female";
// Assign instance method
userProfile.consumeSnack = function(snackType) {
console.log(`${this.userName} is eating ${snackType}`);
};
// Access object properties
console.log(userProfile.userName);
console.log(userProfile.userAge);
console.log(userProfile.gender);
// Invoke object method
userProfile.consumeSnack("matcha mochi");
2. Create with a custom constructor function
Custom constructor functions let you define reusable object blueprints, with properties and methods initialized at instantiation time for consistent object structures.
// Define custom constructor blueprint
function Pet(petName, petAge, petSpecies) {
this.petName = petName;
this.petAge = petAge;
this.petSpecies = petSpecies;
this.playWithToy = function(toyName) {
console.log(`${this.petAge}-year-old ${this.petSpecies} ${this.petName} is playing with a ${toyName}`);
}
}
// Create new instance from constructor
const myCat = new Pet("Mimi", 3, "Ragdoll");
// Access instance properties
console.log(myCat.petName);
console.log(myCat.petAge);
console.log(myCat.petSpecies);
// Invoke instance method
myCat.playWithToy("feather wand");
3. Create using object literal syntax
Object literal (JSON-style) syntax is the most concise pattern for one-off object creation, with properties and methods defined inline during initialization.
// Define object with inline properties and methods
const coffeeShop = {
shopName: "Sunny Bean",
location: "Downtown Chengdu",
customerRating: 4.8,
brewDrink: function(drinkName) {
console.log(`${this.shopName} located in ${this.location} is preparing your ${drinkName}`);
}
};
// Access object properties
console.log(coffeeShop.shopName);
console.log(coffeeShop.location);
console.log(coffeeShop.customerRating);
// Call object method
coffeeShop.brewDrink("oat milk latte");