JavaScript: Object Methods

An object method in javascript is nothing but a function assigned as a property to an object. Now we all know what object properties are in javascript.

var obj = {
    name : 'Neo',
    age : 20
}

console.log(obj.age)

Output: 20

This is a normal object which has some properties inside of it and we can access these properties via the obj variable. So, here object methods play a vast role in assigning themselves to the properties as a function disguised as properties.

Example

var obj = {
    name : 'Neo',
    age : 20,
    
    objMeth : function (){
        console.log(obj.name)
   }
}

obj.objMeth()

Output: Neo

So here we have an object property and inside it, there is a function that can be used to call the properties within it and other things. Next, we have called that property like normally and included the () as we call a function.

We can also access the properties from a function via the 'this' keyword too directly calling the property's name instead of the variable name and then calling.

var obj = {
    name : 'Neo',
    age : 20,
    objMeth : function (){
        console.log(this.name)
    }
}

obj.objMeth()

Output: Neo

Here as we can see I have used the 'this' keyword and what 'this' means is that it points out to the owner of the object which simply means you will have access to all of the properties all long as it is inside with the same object property.

Fri, 10/22/2021 - 15:16

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags