Javascript Object Definition

Introduction

The canonical way of creating a custom object is to create a new instance of Object and add properties and methods to it:

let person = new Object();
person.name = "HTML";
person.age = 29;
person.job = "Software Engineer";

person.sayName = function() {
    console.log(this.name);
};

The previous example can be rewritten using object literal notation as follows:

let person = {
    name: "HTML",
    age: 29,
    job: "Software Engineer",
    sayName() {
        console.log(this.name);
    }
};



PreviousNext

Related