Methods Vs Functions in JavaScript

Well many of us may come across situations where we find it difficult to differentiate between a function and a method. I have also encountered that problem and was tensed until I found the real logic. Trust me, someone asked me this question and at that time I couldn't answer and when I got the answer I started wondering when I would again get a chance to meet the same person. I wish that doesn't happen to anyone. Enough of storytelling, let's get to the point.

Just remember the following line as an answer: “A function that is a property of an object is a method.”.

Now let's dig into it, but first the basics. A function can be defined either by a declaration expression or by a definition expression.

  • Function Declaration Expression: Function when defined with a name.


  • Function Definition Expression: an Anonymous Function assigned to a variable. In JavaScript a function is also considered an object, thus they can be assigned to a variable.


JavaScript won't complain even if you have a named function and still you are assigning it to a variable. Functions defined in this manner also falls into the category of a function definition expression.

Consider the snippet below

The code is simple. We have defined an object with the two properties x and y. Then we have defined a function SayHello. We added two properties SomeMethod and AnotherMethod to the object obj and assigned a function to both of the properties. The tricky part is the function assigned to the AnotherMethod property is a nested function, in other words functions defined inside a function. Now just read the definition once again and ask yourself:
  • Is SomeMethod a property of an object?
  • Is AnotherMethod a property of an object?
  • Is SayHello a property of an object?
  • Is NestedFunction a property of an object?
If you can answer the preceding question the job is done. Let's elaborate now. SomeMethod and AnotherMethod are surely properties of the object obj. Thus it is guaranteed that they are methods.

SayHello

SayHello is a property of which object? Please note the functions defined in this manner are like that of SayHello that becomes a property of a global object that can be invoked directly (in other words SayHello()) or using this keyword (in other words this.SayHello()) hence SayHello is also a method.

Now for the last target, NestedFunction. NestedFunction is not assigned to any property. It is just defined in an inner scope. Thus we can say it is just a function, not a method.

Conclusion
 
 

Up Next
    Ebook Download
    View all
    Learn
    View all