What is Method Invocation Pattern in JavaScript

In this post we will take a look on “Method Invocation Pattern” in JavaScript. In JavaScript when function is defined as property of object then it is known as Method

image

Assume we have a JavaScript object as following. In studentObject object 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 method is known as “Method Invocation Pattern”. We can invoke method using dot operator on object. Method can be invoked as following,


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

A Method can access its parent object using operator this. Let us go ahead and modify studentobject as following. Now you can see that we are accessing other properties of object in 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 grade property with invocation of findgrade method.


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

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

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

3 thoughts on “What is Method Invocation Pattern in JavaScript”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s