In Javascript every function is an object (A).
An Object is collection of {key:value}
pair.
As per MDN:
A method is a function which is a property of an object. There are two kind of methods: Instance Methods which are built-in tasks performed by an object instance, or Static Methods which are tasks that are called directly on an object constructor.
Values can be
*-> Primative: * Primative implies to data type such as number
, string
,boolean
or can be another pair of object
.
-> Function: Since its property of an object, so function is called as Method
.
So, does it means that every function
is a method but every method is not a function
? No
-> If a function is within the lexical environment / environment of an object, then that function is termed as method
, we can invoke that by OurObject.OurMethod()
(B)
var OurObject= {
name : "John snow",
OurMethod: function someFun(paramA, paramB) {
// some code..
}
-> A pure function is, a function which have no object associated with it.
function func(param1, ...args){
// some code...
}
As per Point A, we are saying every function is an object in Javascript, so, a function within within a function will be termed as method
of that function.
From the book ** JavaScript Patterns by Stoyan Stefanov** covers your questions in detail. 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.
Lastly, I would like to give very basic example. Everyone knows that arrays have different methods.
EXACTLY, different METHODS
not FUNCTIONS
. Like push()
, pop()
,slice(),
splice()`.
Why they are methods?
They are methods because this functions are an part of an object, so as per point B, There environment is object, so they are termed as METHODS
.
Cheers!!
For more such update follow @msabir
@thumbone, Maybe I think I had clear your doubts now. Terminology changes based on scope of an object.