Skip to main content

Command Palette

Search for a command to run...

Different methods of writing an object in JavaScript

Updated
Different methods of writing an object in JavaScript
A

Self Taught Developer & Full Stack Self Learned With a Passion for Coding. Strong Node Js & Javascript Skills. Always Eager to Adapt and Take on new Challenges !

There are many ways in javascript to write object. Here, let us only focus on the various ways in which JavaScript allows us to create objects.

Object literal

var obj = { name : "car" }

console.log(obj) // {name: "car"}

‘new’ keyword

var obj = new Object()

obj.name = "car"

console.log(obj) // {name: "car"}

Object.create

let obj1 = {

getFullName: function () {

return `${this.fName} ${this.lName}`

}

}

let obj2 = Object.create(obj1)

obj1.fName = "clark"

obj2.lName = "kent"

console.log(obj2.getFullName()) // clark kent

Constructor function

construction function is user deifined object

function Person(fName,lName){

this.firstName = fName this.lastName = lName

}

var batMan = new Person("bruce","wayne")

batMan.superHero = true

console.log(batMan) // {firstName: "bruce", lastName: "wayne", superHero:true}

class using es6

class Person{

constructor(fName,lName){

this.firstName = fName this.lastName = lName

}

}

var batMan = new Person("bruce","wayne")

batMan.superHero = true

console.log(batMan) // {firstName: "bruce", lastName: "wayne", superHero:true}