📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
What is the design pattern?
The Constructor Pattern
The Constructor Pattern Example
// using constructor function
function User(firstName, lastName, emailId, age){
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
this.age = age;
this.getFullName = function (){
return this.firstName + " " + this.lastName;
}
}
var user1 = new User('Ramesh', 'Fadatare', 'ramesh24@gmail.com', 29);
var user2 = new User('John', 'Cena', 'john@gmail.com', 45);
var user3 = new User('Tony', 'Stark', 'tony@gmail.com', 52);
// Print objects
console.log(user1);
console.log(user2);
console.log(user3);
// access properties
console.log(user1.firstName);
console.log(user1.lastName);
console.log(user1.age);
// calling method
console.log(user1.getFullName());
User {firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh24@gmail.com", age: 29, getFullName: Æ’}
User {firstName: "John", lastName: "Cena", emailId: "john@gmail.com", age: 45, getFullName: Æ’}
User {firstName: "Tony", lastName: "Stark", emailId: "tony@gmail.com", age: 52, getFullName: Æ’}
Ramesh
Fadatare
29
Ramesh Fadatare
// using constructor function
function User(firstName, lastName, emailId, age){
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
this.age = age;
}
// // we extend the function's prototype
User.prototype.getFullName = function () {
return this.firstName + " " + this.lastName;
}
var user1 = new User('Ramesh', 'Fadatare', 'ramesh24@gmail.com', 29);
var user2 = new User('John', 'Cena', 'john@gmail.com', 45);
var user3 = new User('Tony', 'Stark', 'tony@gmail.com', 52);
// Print objects
console.log(user1);
console.log(user2);
console.log(user3);
// access properties
console.log(user1.firstName);
console.log(user1.lastName);
console.log(user1.age);
// calling method
console.log(user1.getFullName());
User {firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh24@gmail.com", age: 29, getFullName: Æ’}
User {firstName: "John", lastName: "Cena", emailId: "john@gmail.com", age: 45, getFullName: Æ’}
User {firstName: "Tony", lastName: "Stark", emailId: "tony@gmail.com", age: 52, getFullName: Æ’}
Ramesh
Fadatare
29
Ramesh Fadatare
Related JavaScript Design Patterns
- JavaScript Factory Pattern with Example //Popular
- JavaScript Builder Pattern Example //Popular
Comments
Post a Comment
Leave Comment