CoffeeScript – Classes and Inheritance

CoffeeScript – Classes and Inheritance ”; Previous Next JavaScript does not provide the class keyword. We can achieve inheritance in JavaScript using objects and their prototypes. Every object have their own prototype and they inherit functions and properties from their prototypes. Since the prototype is also an object, it also has its own prototype. Though the prototypal inheritance is far more powerful than classic inheritance, it is difficult and confusing for novice users. Classes in CoffeeScript Addressing to this problem, CoffeeScript provides a basic structure known as class which is built using the JavaScript”s prototypes. You can define a class in CoffeeScript using the class keyword as shown below. class Class_Name Example Consider the following example, here we have created a class named Student using the keyword class. class Student If you compile the above code, it will generate the following JavaScript. var Student; Student = (function() { function Student() {} return Student; })(); Instantiating a class We can instantiate a class using the new operator just like other object oriented programming languages as shown below. new Class_Name You can instantiate the above created (Student) class using the new operator as shown below. class Student new Student If you compile the above code, it will generate the following JavaScript. var Student; Student = (function() { function Student() {} return Student; })(); new Student; Defining a Constructor A constructor is 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 name constructor as shown below. class Student constructor: (name)-> @name = name In here, we have defined a constructor and assigned the local variable name to the instance variable. The @ operator is an alias to the this keyword, it is used to point the instance variables of a class. If we place @ before an argument of the constructor, then it will be set as an instance variable automatically. Therefore, the above code can be written simply as shown below − class Student constructor: (@name)-> Example Here is an example of a constructor in CoffeeScript. Save it in a file with the name constructor_example.coffee #Defining a class class Student constructor: (@name)-> #instantiating a class by passing a string to constructor student = new Student(“Mohammed”); console.log “the name of the student is :”+student.name Compiling the code Open command prompt and compile the above example as shown below. c:>coffee -c constructor_example.coffee On executing the above command it will produce the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var Student, student; Student = (function() { function Student(name) { this.name = name; } return Student; })(); student = new Student(“Mohammed”); console.log(“The name of the student is :”+student.name); }).call(this); Executing the Code Run the above example by executing the following command on the command prompt. coffee constructor_example.coffee On running, the above example gives you the following output. The name of the student is :Mohammed Instance Properties Same as in objects, we can also have properties within a class. And these are known as instance properties. Example Consider the following example. In here, we have created variables (name, age) and a function (message()) within the class and accessed them using its object. Save this example in a file named instance_properties_example.coffee #Defining a class class Student name=”Ravi” age=24 message: -> “Hello “+name+” how are you” #instantiating a class by passing a string to constructor student = new Student(); console.log student.message() On compiling, the above code generates the following output. // Generated by CoffeeScript 1.10.0 (function() { var Student, student; Student = (function() { var age, name; function Student() {} name = “Ravi”; age = 24; Student.prototype.message = function() { return “Hello ” + name + ” how are you”; }; return Student; })(); student = new Student(); console.log(student.message()); }).call(this); Static Properties We can define static properties in the class. The scope of the static properties is restricted within the class and we create static functions using the this keyword or its alias @ symbol and we have to access these properties using the class name as Class_Name.property. Example In the following example, we have created a static function named message. and accessed it. Save it in a file with the name static_properties_example.coffee. #Defining a class class Student @message:(name) -> “Hello “+name+” how are you” console.log Student.message(“Raju”) Open the command prompt and compile the above CoffeeScript file using the following command. c:>coffee -c static_properties_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var Student; Student = (function() { function Student() {} Student.message = function(name) { return “Hello ” + name + ” how are you”; }; return Student; })(); console.log(Student.message(“Raju”)); }).call(this); Execute the above coffeeScript in command prompt as shown below. c:>coffee static_properties_example.coffee On executing, the above example gives you the following output. Hello Raju how are you Inheritance In CoffeeScript, we can inherit the properties of one class in another class using extends keyword. Example Following is an Example of inheritance in CoffeeScript. In here, we have two classes namely Add and My_class. We inherited the properties of class named Add in the class My_class, and accessed them using the extends keyword. #Defining a class class Add a=20;b=30 addition:-> console.log “Sum of the two numbers is :”+(a+b) class My_class extends Add my_class = new My_class() my_class.addition() CoffeeScript uses prototypal inheritance behind the scenes. In CoffeeScript, whenever we create instances, the parent class”s constructor is invoked until we override it. We can invoke the constructor of the parent class from the subclass, using the super() keyword as shown in the example given below. #Defining a class class Add constructor:(@a,@b) -> addition:=> console.log “Sum of the two numbers is :”+(@a+@b) class Mul extends Add constructor:(@a,@b) -> super(@a,@b) multiplication:-> console.log “Product of the two numbers is :”+(@a*@b) mul = new Mul(10,20) mul.addition() mul.multiplication() Dynamic Classes CoffeeScript uses prototypal inheritance to automatically inherit all the instance properties of a class. This ensures that classes are dynamic;

CoffeeScript – Ajax

CoffeeScript – Ajax ”; Previous Next AJAX is a web development technique for creating interactive web applications. AJAX stands for Asynchronous JavaScript and XML. It is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script. Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display. Conventional web applications transmit information to and from the server using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background. In general, we use jQuery to work with Ajax. Following is an example of Ajax and jQuery <html> <head> <title>The jQuery Example</title> <script type = “text/javascript” src = “https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script> <script type = “text/javascript” language = “javascript”> $(document).ready(function() { $(“#driver”).click(function(event){ $(”#stage”).load(”/jquery/result.html”); }); }); </script> </head> <body> <p>Click on the button to load /jquery/result.html file −</p> <div id = “stage” style = “background-color:cc0;”> STAGE </div> <input type = “button” id = “driver” value = “Load Data” /> </body> </html> Here load() initiates an Ajax request to the specified URL /coffeescript/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming that our /jquery/result.html file has just one HTML line − <h1>THIS IS RESULT…</h1> When you click the given button, then result.html file gets loaded. CoffeeScript with Ajax We can rewrite the above example using CoffeeScript as shown below. <html> <head> <title>The jQuery Example</title> <script type = “text/javascript” src = “https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script> <script src=”http://coffeescript.org/extras/coffee-script.js”></script> <script type=”text/coffeescript”> $(document).ready -> $(”#driver”).click (event) -> $(”#stage”).load ”/jquery/result.html” return return </script> </head> <body> <p>Click on the button to load /jquery/result.html file -</p> <div id = “stage” style = “background-color:cc0;”> STAGE </div> <input type = “button” id = “driver” value = “Load Data” /> </body> </html> Print Page Previous Next Advertisements ”;

CoffeeScript – Regular Expressions

CoffeeScript – Regular Expressions ”; Previous Next A regular expression is an object that describes a pattern of characters JavaScript supports. In JavaScript, RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text. Regular Expressions in CoffeeScript The regular expressions in CoffeeScript are same as JavaScript. Visit the following link to see the regular expressions in JavaScript − javascript_regular_expressions Syntax A regular expression in CoffeeScript is defined by placing the RegExp pattern between the forward slashes as shown below. pattern =/pattern/ Example Following is an example of regular expressions in CoffeeScript. In here, we have created an expression that finds out the data that is in bold (data between <b> and </b> tags). Save this code in a file with name regex_example.coffee input_data =”hello how are you welcome to <b>Tutorials Point.</b>” regex = /<b>(.*)</b>/ result = regex.exec(input_data) console.log result Open the command prompt and compile the .coffee file as shown below. c:> coffee -c regex_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var input_data, regex, result; input_data = “hello how are you welcome to <b>Tutorials Point.</b>”; regex = /<b>(.*)</b>/; result = regex.exec(input_data); console.log(result); }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee regex_example.coffee On executing, the CoffeeScript file produces the following output. [ ”<b>Tutorials Point.</b>”, ”Tutorials Point.”, index: 29, input: ”hello how are you welcome to <b> Tutorials Point.</b>” ] heregex The complex regular expressions we write using the syntax provided by JavaScript are unreadable, therefore to make Regular expressions more readable, CoffeeScript provides an extended syntax for regular expressions known as heregex. Using this syntax, we can break the normal regular expressions using whitespaces and we can also use comments in these extended regular expressions, thus making them more user friendly. Example The following example demonstrates the usage of the advanced regular expressions in CoffeeScript heregex. In here, we are rewriting the above example using the advanced regular expressions. Save this code in a file with name heregex_example.coffee input_data =”hello how are you welcome to Tutorials Point.” heregex = /// <b> #bold opening tag (.*) #the tag value </b> #bold closing tag /// result = heregex.exec(input_data) console.log result Open the command prompt and compile the .coffee file as shown below. c:> coffee -c heregex_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var heregex, input_data, result; input_data = “hello how are you welcome to <b> Tutorials Point.</b>”; heregex = /<b>(.*) </b>/; result = heregex.exec(input_data); console.log(result); }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee heregex_example.coffee On executing, the CoffeeScript file produces the following output. [ ”<b>Tutorials Point.</b>”, ”Tutorials Point.”, index: 29, input: ”hello how are you welcome to <b>Tutorials Point.</b>” ] Print Page Previous Next Advertisements ”;

CoffeeScript – Home

CoffeeScript Tutorial PDF Version Quick Guide Resources Job Search Discussion CoffeeScript is a light weight language which transcompiles into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language. Audience This tutorial has been prepared for beginners to help them understand the basic functionality of CoffeeScript to build dynamic webpages and web applications. Prerequisites For this tutorial, it is assumed that the readers have a prior knowledge of HTML coding and JavaScript. It would help if the reader has some prior exposure to object-oriented programming concepts and a general idea on creating online applications. Execute CoffeeScript Online For most of the examples given in this tutorial, you will find Try it option, so just make use of this option to transcompile your CoffeeScript programs to JavaScript programs on the spot and enjoy your learning. Try the following example using the Try it option available at the top right corner of the below sample code box − console.log “Hello Welcome to Tutorials point” Print Page Previous Next Advertisements ”;

CoffeeScript – Splat

CoffeeScript – Splat ”; Previous Next In the previous chapters, we have seen how to define a function and invoke a function and pass arguments to it. In general, we can pass a fixed number of arguments to a function. While programming, we may face situations where we need to pass variable arguments to these functions. In JavaScript, we use objects to accept variable number of arguments to a function. CoffeeScript provides a feature called splats to pass multiple arguments to functions. We use splats in functions by placing three dots after the argument name and, it is denoted by … Syntax Given below is the syntax of accepting multiple arguments within a function using splats. my_function = (arguments…)-> ………… ………… ………… Example Following is an example of accepting multiple arguments within a function, using splats. Here we have defined a function named indian_team() using splats. We are calling this function thrice and we are passing 4 players, 6 players, and full squad simultaneously, each time we call it. Since we have used splats in the function definition, it accepts variable number of arguments each time we call it. Save this code in a file with name splats_definition.coffee indian_team = (first, second, others…) -> Captain = first WiseCaptain = second team = others console.log “Captain: ” +Captain console.log “Wise captain: ” +WiseCaptain console.log “Other team members: ” +team #Passing 4 arguments console.log “############## Four Players ############” indian_team “Mahendra Singh Dhoni”, “Virat Kohli”, “Shikhar Dhawan”, “Rohit Sharma” #Passing 6 arguments console.log “############## Six Players ############” indian_team “Mahendra Singh Dhoni”, “Virat Kohli”, “Shikhar Dhawan”, “Rohit Sharma”, “Gurkeerat Singh Mann”, “Rishi Dhawan” #Passing full squad console.log “############## Full squad #############” indian_team “Mahendra Singh Dhoni”, “Virat Kohli”, “Shikhar Dhawan”, “Rohit Sharma”, “Gurkeerat Singh Mann”, “Rishi Dhawan”, “Ravindra Jadeja”, “Axar Patel”, “Jasprit Bumrah”, “Umesh Yadav”, “Harbhajan Singh”, “Ashish Nehra”, “Hardik Pandya”, “Suresh Raina”, “Yuvraj Singh”, “Ajinkya Rahane” Open the command prompt and compile the .coffee file as shown below. c:> coffee -c splats_definition.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var indian_team, slice = [].slice; indian_team = function() { var Captain, WiseCaptain, first, others, second, team; first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : []; Captain = first; WiseCaptain = second; team = others; console.log(“Captain: ” + Captain); console.log(“Wise captain: ” + WiseCaptain); return console.log(“Other team members: ” + team); }; console.log(“############## Four Players ############”); indian_team(“Mahendra Singh Dhoni”, “Virat Kohli”, “Shikhar Dhawan”, “Rohit Sharma”); console.log(“############## Six Players ############”); indian_team(“Mahendra Singh Dhoni”, “Virat Kohli”, “Shikhar Dhawan”, “Rohit Sharma”, “Gurkeerat Singh Mann”, “Rishi Dhawan”); console.log(“############## Full squad #############”); indian_team(“Mahendra Singh Dhoni”, “Virat Kohli”, “Shikhar Dhawan”, “Rohit Sharma”, “Gurkeerat Singh Mann”, “Rishi Dhawan”, “Ravindra Jadeja”, “Axar Patel”, “Jasprit Bumrah”, “Umesh Yadav”, “Harbhajan Singh”, “Ashish Nehra”, “Hardik Pandya”, “Suresh Raina”, “Yuvraj Singh”, “Ajinkya Rahane”); }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee splats_definition.coffee On executing, the CoffeeScript file produces the following output. ############## Four Players ############ Captain: Mahendra Singh Dhoni Wise captain: Virat Kohli Other team members: Shikhar Dhawan,Rohit Sharma ############## Six Players ############ Captain: Mahendra Singh Dhoni Wise captain: Virat Kohli Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan ############## Full squad ############# Captain: Mahendra Singh Dhoni Wise captain: Virat Kohli Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan,Ravindra Jadeja,Axar Patel,Jasprit Bumrah,Umesh Yadav,Harbhajan Singh,Ashish Nehra,Hardik Pandya,Suresh Raina,Yuvraj Singh,Ajinkya Rahane Calling Functions using Splats We can also call a function using splats. For that, we have to create an array holding the elements we need to pass to the function, and we have to call the function by passing the array suffixed by three dots as shown below. my_function values… Example Following is an example of calling a function using splats. Save this code in a file with name splats_call.coffee indian_team = (first, second, others…) -> Captain = first WiseCaptain = second team = others console.log “Captain: ” +Captain console.log “Wise captain: ” +WiseCaptain console.log “Other team members: ” +team squad = [ “Mahendra Singh Dhoni” “Virat Kohli” “Shikhar Dhawan” “Rohit Sharma” “Gurkeerat Singh Mann” “Rishi Dhawan” “R Ashwin” “Ravindra Jadeja” “Axar Patel” “Jasprit Bumrah” “Umesh Yadav” “Harbhajan Singh” “Ashish Nehra” “Hardik Pandya” “Suresh Raina” “Yuvraj Singh” “Ajinkya Rahane” ] indian_team squad… Open the command prompt and compile the .coffee file as shown below. c:> coffee -c splats_call.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var indian_team, squad, slice = [].slice; indian_team = function() { var Captain, WiseCaptain, first, others, second, team; first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : []; Captain = first; WiseCaptain = second; team = others; console.log(“Captain: ” + Captain); console.log(“Wise captain: ” + WiseCaptain); return console.log(“Other team members: ” + team); }; squad = [“Mahendra Singh Dhoni”, “Virat Kohli”, “Shikhar Dhawan”, “Rohit Sharma”, “Gurkeerat Singh Mann”, “Rishi Dhawan”, “R Ashwin”, “Ravindra Jadeja”, “Axar Patel”, “Jasprit Bumrah”, “Umesh Yadav”, “Harbhajan Singh”, “Ashish Nehra”, “Hardik Pandya”, “Suresh Raina”, “Yuvraj Singh”, “Ajinkya Rahane”]; indian_team.apply(null, squad); }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee splats_call.coffee On executing, the CoffeeScript file produces the following output. Captain: Mahendra Singh Dhoni Wise captain: Virat Kohli Other team members: Shikhar Dhawan,Rohit Sharma,Gurkeerat Singh Mann,Rishi Dhawan,R Ashwin,Ravindra Jadeja,Axar Patel,Jasprit Bumrah,Umesh Yadav,Harbhajan Singh,Ashish Nehra,Hardik Pandya,Suresh Raina,Yuvraj Singh,Ajinkya Rahane Splats with a Tailing Argument We can also pass tailing arguments to splats. In the example given below, we have passed a tailing argument named last after the splat. Save this example in a file with the name tailing_arguments.coffee indian_team = (first, second, others…, last) -> Captain = first WiseCaptain = second team = others Wicketkeeper =last console.log “Captain: ” +Captain console.log “Wise captain: ” +WiseCaptain console.log “Wicket keeper is:”+last console.log “Other team members: ” +team squad = [ “Mahendra Singh Dhoni” “Virat Kohli” “Shikhar Dhawan” “Rohit Sharma” “Gurkeerat Singh Mann” “Rishi Dhawan” “R Ashwin” “Ravindra Jadeja” “Axar Patel” “Jasprit Bumrah” “Umesh