Content |
---|
ES6 Class syntax |
Object constructor |
Object’s create method |
Object literal syntax |
Function constructor |
Function constructor with prototype |
There are many ways to create objects in javascript as below
-
ES6 Class syntax: ES6 introduces class feature to create the objects
class Person { constructor(name) { this.name = name } } var object = new Person("Sudheer")
-
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()
-
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 is equivalent to create method when it passes null as parameter
var 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("Sudheer")
-
Function constructor with prototype: This is similar to function constructor but it uses prototype for their properties and methods,
function Person() {} Person.prototype.name = "Sudheer" var object = new Person()