Q: What is the difference between a function and a method in JS?

17 August 2015

Gosh, I always hated it… In this language you have methods. That language calls them functions. The other one has routines, etc… :)

So, today I’ve digged the book — still around 20% only, but progressing -, and the following line came up to me:

Properties that contain functions are generally called methods, as in…

So, context promotes a function to method. It also implies, that methods are able to access the values stored in their host object, meanwhile simple functions will work mostly on global scoped values and only on values, that are created within them, or passed to them.

Actually, here is an awesome answer found on Stackoverflow by Andrew Edgecombe, that makes is much clearer than my current skill level on clarification:

A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).
All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.
* It is implicitly passed for the object for which it was called.
 * It is able to operate on data that is contained within the class (remembering that an object is an instance of a class — the class is the definition, the object is an instance of that data). (this is a simplified explanation, ignoring issues of scope etc.)

Originally published at notes-andyskw.rhcloud.com on August 17, 2015.

Show your support

Clapping shows how much you appreciated András Iványi’s story.