Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
Method vs Functions
"Methods are really just owned functions, our string owns that function, upper"
I understand what a function is, but I'm not sure about methods. Are they the same thing?
A function is a chunk of code that does something when called.
A method is similar that it does something when used, but it’s on a case-by-case basis and manipulates an object in some way via its properties.
So, you could choose a single element in the DOM and change it’s backgroune color by using the appropriate method. You could put that method into a function and create a click event that will trigger the method to do its thing on every click.
“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 can be performed without the need of an object instance.”
Cooper Runstein11,850 Points
mryoung is hitting most of the key point, the key difference is a function is called directly by name, while a method is called by a name that is associated with an object. If you have a global function floating around in the global space, or a function nested within another function, that's a function. When you have a class with a function within it, that's a method. One of the key ways to tell is a method needs the object associated with it to be passed to it, if you see:
def my_method(self, data):
The self in the method deceleration gives away the fact that it's a method.
That said, rarely, if ever, outside of academic quizzes or whatever, will you need to know the difference, by name, rather you'll need to know the difference in functionality, this being access to certain data:
self.color = 'red'
#Has access to the MyObject's color
#Does not have access to MyObject's color