Javascript - Object Literal with function

Introduction

ES6 has a short notation to write functions in an object literal.

const price = 4.20, count = 20; 
const myOrder = { 
        price, 
        count, 
        getTotal() { 
                return this.price * this.count; 
        } 
}; 
console.log(myOrder.getTotal()); 

Here, we no longer need the keyword function.

When we use the function shorthand within an object literal, this refers to the context of the code just like an arrow function.

It does not refer to the object that contains the function.

Related Topic