Open In App

Explain Class Methods in Coffeescript

Last Updated : 22 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

CoffeeScript is a lightweight language that compiles into JavaScript. As compared to JavaScript, it provides simple and easy-to-learn syntax avoiding the complex syntax of JavaScript. CoffeeScript is influenced by languages such as JavaScript, YAML, Ruby, and Python and has also influenced languages that are LiveScript, and MoonScript.

Installation of CoffeeScript

Install locally for a project, use the following command:

npm install --save-dev coffeescript

To Globally install to execute the .coffee files anywhere, use the following command:

npm install --global coffeescript

Methods

Methods of the class are functions declared, and defined inside the class. Methods define the behavior of objects. Methods or functions can be of two types methods with parameters or methods without parameters. If the method is not taking any parameters then you do not need to worry about passing arguments while calling the method. A constructor is also a function that is invoked when we instantiate a class, its main purpose is to initialize the instance variables. In CoffeeScript, you can define a constructor just by creating a function with the name constructor.

Auto access methods

There are two ways to access methods one is by creating an instance or object of the class and using that instance we can call methods that are declared inside the class body and we call it a class method. The second way to access methods of the class is by using the class name itself and we call it an instance method.

Method with parameters

A method having n number of parameters is referred to as a method with parameters.

Example: Below is an example of a method with parameters.

Javascript




class Gfg
    method: (name,profession)->
        console.log name + " is engineer at #{profession}."
 
p1 = new Gfg
p1.method("devendra","GeeksforGeeks")


Output: 

devendra is engineer at GeeksforGeeks

Method without parameters

This is also just similar to method with parameter but the basic difference that defines both separate is parameters. The method without parameters name itself suggests that it has no parameters.

Example: Below is an example of method without parameters. Here, we do not pass any argument at function or method call but actual method taking parameters so while putting output on console method will print undefined in place of the parameter value.

Javascript




class Gfg   
    method: (name,profession)->
        console.log name + " is engineer at #{profession}."
 
p1 = new Gfg
p1.method()


Output: 

undefined is engineer at undefined

Reference: https://coffeescript-cookbook.github.io/chapters/classes_and_objects/class-methods-and-instance-methods



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads