Methods: functions that live on a class
Read before 2.2.7b Lab — Method with no params. About 4 minutes.
By the end of this reading you should be able to answer:
- How does a method declaration differ from a
functiondeclaration? - Can you spot a method in a 6-line class body?
A method is a function that lives inside a class body and has access to this. The only syntax difference from a regular function is that you drop the function keyword.
What you'll learn from it:
- Inside a class body, write
methodName(params) { ... }— nofunctionkeyword. - Adding
functionbefore the method name is a syntax error; the engine won't run the file. - A method is available on every instance of the class — you don't create it separately.
- Calling a method on an instance:
instance.methodName(args).
Try it: