Method vs Functions, and other questions

To answer your title question as to what is the difference between a ‘function’ and a ‘method’.

It’s semantics and has to do with what you are trying to express.

In JavaScript every function is an object. An object is a collection of key:value pairs. If a value is a primitive (number, string, boolean), or another object, the value is considered a property. If a value is a function, it is called a ‘method’.

Within the scope of an object, a function is referred to as a method of that object. It is invoked from the object namespace MyObj.theMethod(). Since we said that a function is an object, a function within a function can be considered a method of that function.

You could say things like “I am going to use the save method of my object.” And “This save method accepts a function as a parameter.” But you generally wouldn’t say that a function accepts a method as a parameter.

Btw, the book JavaScript Patterns by Stoyan Stefanov covers your questions in detail, and I highly recommend it if you really want to understand the language. Here’s a quote from the book on this subject:

So it could happen that a function A, being an object, has properties and methods, one of which happens to be another function B. Then B can accept a function C as an argument and, when executed, can return another function D.

Leave a Comment