Object Oriented Javascript

Mind your Object

I saw a cat on road, Cat who has name, gender, age, weight and colour etc, who can perform activity eat which represent its behaviour.

Here Cat is an Object and name, gender, age, weight represent attributes.

Whereas activities (behaviour) like eat is method of cat object.

In javascript object define with {}, so we can write cat object by considering above attributes and methods as follow:

Object Literals

Object Literals is the way to define object in javascript which is convenient for object which consist for single method.

const cat ={ 
    name:"Jeff",
    gender:"Male",
    eat:function(){
        console.log('eat');
    },
}

Object literal syntax is not good way to define object if object has more than one method.

Cat can also run, breath, sleep and so on.

Therefore, for one ore more methods in particular object (behaviour object) we can define Factories

Factories
function cat(name){ 
    return { 
        name,
        gender:"Male",
        sleep:function(){
            console.log('sleep');
        },
        eat:function(){
            console.log('eat');
        },
    };
}

const myCat = cat('Jeff');
myCat.sleep();

Note name attribute of cat method we have not specified value of it, If key and value are same we can remove the value from the code, therefor instead of name:name we specified name.

Constructor