Advanced JS Objects

Creating a JS object using function

JS object can be created using a function. This function accept any arguments which will be assigned to property values.

				
					// Defining a function in order to create multiple objects using below function
function createStudent(name, age, country, company){
    const student = {};  
    student["name"] = name
    student["age"] = age
    student["country"] = country
    student["company"] = company
    return student
}

// creating objects
const s1 = createStudent("Mayur", 25, "USA", "Apple")
const s2 = createStudent("Swapnil", 23, "Singapore", "Google")

console.log(s1)
console.log(s2)

// output :
{ name: 'Mayur', age: 25, country: 'USA', company: 'Apple' }
{ name: 'Swapnil', age: 23, country: 'Singapore', company: 'Google' }

				
			

JS Object Constructor

JS object constructor can be created using ‘this’ keyword and it is used to create as many object as possible. It is also called as constructor function. Constructor functions are called using ‘new’ keyword. 

Note : object declaration and return statement inside constructor function is not needed as it is automatically being taken care by JS. A constructor function is always starts with upper case letter.

				
					// Defining a constructor function
function Student(name, age, country, company){
    this["name"] = name
    this["age"] = age
    this["country"] = country
    this["company"] = company
}

// Calling constructor function using 'new' keyword
const s1 = new Student("Mayur", 25, "USA", "Apple")
const s2 = new Student("Swapnil", 23, "Singapore", "Google")

console.log(s1)
console.log(s2)

// output : 
Student { name: 'Mayur', age: 25, country: 'USA', company: 'Apple' }
Student {
  name: 'Swapnil',
  age: 23,
  country: 'Singapore',
  company: 'Google'
}

				
			

Creating JS object using instance

A shortcut method to create objects on the go using object instance. 

				
					const car = new Object({
    make:"Honda",
    model:"CRV",
    year:2022,
    color:"white"
})

console.log(car)

// output :
{ make: 'Honda', model: 'CRV', year: 2022, color: 'white' }
				
			

Flexible Constructor Arguments

Constructor arguments are also flexible just like normal function arguments in JS. Flexible meaning it is not necessary to pass these arguments while creating an object in JS.

				
					
function AppleDevice(deviceName, deviceOS, display){
    this.deviceName = deviceName
    this.deviceOS = deviceOS
    this.display = display
    console.log(`${deviceName} with ${deviceOS}`)
}

const device1 = new AppleDevice() // Not passing any argument
device1.deviceName = "iPhone14"   // Passing argument at later stage 
console.log(device1)

// output :
undefined with undefined
AppleDevice {
  deviceName: undefined,
  deviceOS: undefined,
  display: undefined
}
				
			

Calling constructor without new keyword

A constructor function is essentially just a normal function which can be invoked without ‘new’ keyword.

‘new.target’ is used to determine if an constructor function is invoked with ‘new’ keyword. If a same function is used as a normal function as well as constructor function then we can make that separation using ‘new.target’

				
					
function AppleDevice(deviceName, deviceOS){
    if (!new.target){
        return `Get an ${deviceName} with ${deviceOS}`  // returning a string if function invoked without 'new' 
    }
    this.deviceName = deviceName
    this.deviceOS = deviceOS
}

const device1 = AppleDevice("iPhone13", "iOS14")  // Invoking constructor function without 'new' keyword
const device2 = new AppleDevice("iPhone14", "iOS16") // Invoking constructor function with 'new' keyword

console.log(device1)
console.log(device2)

// Output :
Get an iPhone13 with iOS14  // Invoked as a normal function
AppleDevice { deviceName: 'iPhone14', deviceOS: 'iOS16' }  // Invoked as a constructor function
				
			

Calling function using 'call()' property

We can call a function by providing a reference of any other object using ‘call()’ property. 

				
					
let account = {
    name:"Mayur",
    number:1234,
    amount:5000,
    addAmt:function(){
        this.amount += 1000
    }
}

let accountManager = {
    name:"Tom",
    managingAccountFor:account.name,
    addAmt:account.addAmt    
}

accountManager.addAmt.call(account)  // Passing reference of account object using 'call' property

console.log(account)
console.log(accountManager)

// Output :
{
  name: 'Mayur',
  number: 1234,
  amount: 6000,
  addAmt: [Function: addAmt]
}
{
  name: 'Tom',
  managingAccountFor: 'Mayur',
  addAmt: [Function: addAmt]
}

				
			

Assignments

  1. Create two JS objects by defining a function named as getEmployeeInfo that accepts arguments such as employeeName, salary, department.
  2. Define a constructor function named as Country that accepts arguments such as countryName, population & currency. Invoke this constructor function using ‘new’ keyword.
  3. Define a constructor function named as Course that accepts arguments such as courseName, tuitionFees, duration.  Invoke this constructor function with and without ‘new’ keyword. Print ‘Welcome’ message if invoke using ‘new’ keyword.
  4. Create an object ‘pfAccount’ with properties name, number, accBalance & addBalance function to increase balance by 2000. Create another object named as Employee with properties name, managingPfAccountFor, addBalance. Use ‘call()’ to pass object reference of ‘pfAccount’