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}