What is Method Invocation Pattern in JavaScript

In this article we will have a look at the "Method Invocation Pattern" in JavaScript. In JavaScript, when a function is defined as a property of an object then it is known as a Method.

Method-Invocation-Pattern-in-JavaScript.jpg

Assume we have a JavaScript object as in the following. In the studentObject object the property findgrade is a function. So we can say findgrade is a method.

var studentObject =

            {

                name: "dj",

                marks: 89,

                findgrade: function (marks) {

                    if (marks > 75) {

                        return "Grade A ";

                    }

                    else {

                        return "Grade B ";

                    }

                }

            }

Invocation of a method is known as "Method Invocation Pattern". We can invoke a method using the dot operator on the objectA . Method can be invoked as in the following:

var grade = studentObject.findgrade(99);
alert(grade);


A Method can access its parent object using the operator this. Let us go ahead and modify the studentobject as in the following. Now you will see that we are accessing other properties of the object in the method using this operator.

var studentObject =
            {
                name:
"dj",
                marks: 89,
                grade :
null,
                findgrade:
function (marks) {
                   
if (marks > 75) {
                       
this.grade = "A";
                    }
                   
else {
                       
this.grade = "B";
                    }
                }
            }

Now we can set the grade property with the invocation of the findgrade method.

studentObject.findgrade(99);
               
var grd = studentObject.grade;
                alert(grd);

Binding of the method to the object happens when we execute the method. In this way we can work with Methods and the Method Invocation Pattern in JavaScript. I hope you find this article useful. Thanks for reading.
 

Up Next
    Ebook Download
    View all
    Learn
    View all