Skip to main content

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.

Tags
Submitted by arilio666 on October 22, 2021

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.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.