Saturday 22 December 2018

Is function keyword required in defining functions in object literals?

From EcmaScript 6 onwards, you no need to specify function keyword while defining the functions in object literals.

Let me explain with an example.

HelloWorld.js
var emp1 = {
  firstName : "Krishna",
  lastName : "Gurram",
  
  printEmployeeInfo : function(){
    console.log("firstName : " + this.firstName);
    console.log("lastName : " + this.lastName);
  }
}

emp1.printEmployeeInfo();

Output
firstName : Krishna
lastName : Gurram

As you see HelloWorld.js file, I defined printEmployeeInfo method using function keyword. From EcmaScript 6 onwards, you no need to use function keyword.

You can define printEmployeeInfo() method like below.

printEmployeeInfo(){
    console.log("firstName : " + this.firstName);
    console.log("lastName : " + this.lastName);
  }

HelloWorld.js

var emp1 = {
  firstName : "Krishna",
  lastName : "Gurram",
  
  printEmployeeInfo(){
    console.log("firstName : " + this.firstName);
    console.log("lastName : " + this.lastName);
  }
}

emp1.printEmployeeInfo();


Previous                                                 Next                                                 Home

No comments:

Post a Comment