Methods: Methods are variable functions defined inside the class. Methods are the behavior of objects, they describe the properties of an object, and can modify the state of the object. Objects can also contain methods. An object has its attributes and methods. We can create many instances of a class, and each object will have its value of class properties.
The functions can be of two types – with arguments and without arguments. If a function does not require arguments, we don’t need to worry about it while invoking the function. Let us see both types of functions defined inside the class with their functioning.
Methods without Parameters: If a function does not require arguments, we don’t need to worry about it while invoking the function. It will be more clear through the below example.
Example: In the below example, we are defining the method “play” and a constructor which takes two arguments inside class MyClass. To access the variable methods of class ‘.’ operator is used with an object. First, we created an object p1, and when the class is instantiated constructor will be called and it will print “Sam is 12 years old”. Then, we are accessing the play method using ‘.’ notation on the p1 object, and when the play() function is invoked, it will be executed, and “Sam likes to Play Football” will be printed.
Javascript
class MyClass constructor: (@name,@age) -> console.log @name + " is #{@age} years old." play: -> console.log @name + " likes to play Football." p1 = new MyClass "Sam" , "12" p1.play() |
Output:
Methods with Parameters: The functions that require arguments are referred to as methods with parameters. Let us understand through example, how to create a function with parameters and pass arguments to the function when called.
Example:
Javascript
class MyClass fun: (name,age)-> console.log name + " is #{age} years old." p1 = new MyClass p1.fun( "Sheetal" , "20" ) |
Output: When fun() is invoked using object p1, we pass its arguments name – “Sheetal”, and age – “20” to it. This will execute function fun and print “Sheetal is 20 years old”.
Same example but this time we don’t pass any argument to the “fun” function, the following will be the output.
Javascript
class MyClass fun: (name,age)-> console.log name + " is #{age} years old." p1 = new MyClass p1.fun() |
Output: Since we didn’t pass any argument to the function fun(), it is showing undefined at the place of name and age.