Front-End Interview Questions
Dimple Kumari
Front-end Developer | HTML, CSS, Javascript, React Js, Accessibility, SEO & Network Optimization
Curious about the various ways to create objects in JavaScript?
In my article, I've explained the fundamental ways to create objects in JavaScript, from the classics to the modern ES6 syntax. ??
Object constructor: The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.
var object = new Object();
The Object() is a built-in constructor function so "new" keyword is not required. the above can be written as:
var object = Object();
Object’s create method: The create method of Object creates a new object by passing the prototype object as a parameter
var object = Object.create(null);
Object literal syntax: The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.
领英推荐
var object = {
name: "Dimple",
age: 25
};
Object literal property values can be of any data type, including array, function, and nested object.
Function constructor: Create any function and apply the new operator to create object instances,
function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person("Dimple");
Function constructor with prototype: This is similar to function constructor but it uses prototype for their properties and methods,
function Person() {}
Person.prototype.name = "Dimple";
var object = new Person();
ES6 Class syntax: ES6 introduces class feature to create the objects
class Person {
constructor(name) {
this.name = name;
}
}
var object = new Person("Dimple");
Singleton pattern: A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don’t accidentally create multiple instances.
var object = new (function () {
this.name = "Dimple";
})();
Thank You for Reading!
If you found this post informative and valuable, I’d love for you to connect with me for more front-end development insights. Follow me here on Medium and connect with me on LinkedIn to stay updated on the latest in web development, design, and more.
18 ? ?? I enjoy building softwares | Software Development Engineer | TypeScript | Go
1 年Very useful Dimple!
Front-end Developer | HTML, CSS, Javascript, React Js, Accessibility, SEO & Network Optimization
1 年Check out my latest article on JavaScript object creation! ?? #JavaScript #FrontEndDev