I always have difficulty grasping new concepts without seeing a real, basic, working example of what I am reading about. While I like the other explanation on stackoverflow, I’d really like to see a very basic example showing the difference between methods and functions in JavaScript that I can quickly run to learn more.
I always have difficulty grasping new concepts without seeing a real, basic, working example
Share
A
methodis just a function that is apropertyof an object. It’s not a different type of object in javascript, but rathermethodis just the descriptive name given to afunctionthat is defined as apropertyof an object.In this example,
gois a method on themyObjobject.When a method is called as in the above example
myObj.go(), then the value of thethispointer is set to the object that was involved in the invocation of the method (in this casemyObj).Since global functions are also implicitly properties on the
windowobject, one could say that global functions are also methods on thewindowobject, but you do not need thewindowdesignation in order to call them.Local functions like
inner()in this function are just functions and not methods as they are not attached to a particular object: