Use CoffeeScrip to write javascript code and javascript code in a elegant way

Source: Internet
Author: User
Tags variable scope coffeescript to javascript

Use CoffeeScrip to write javascript code and javascript code in a elegant way

JavaScript is undoubtedly one of the greatest web inventions. Almost all the dynamic effects of web pages are based on its rich computing capabilities. Moreover, its capabilities are becoming increasingly powerful under various new JavaScript Engines, such as Google Chrome's V8 Engine.

However, because it was born too early, many syntax definitions seem to be inefficient today, and some more advanced syntax forms cannot be added to the current JavaScript language due to historical reasons, it can be said that it is a pity.

Many geniuses in the world are working to build better JavaScript. There have been many attempts, and the most promising ones are CoffeeScript and TypeScript. In the face of CoffeeScript, I feel like nothing, and TypeScript has aroused my great interest. Like TypeScript, CoffeeScript is compiled into JavaScript language, which enhances the JavaScript expression capability. This article is about CoffeeScript, and TypeScript will be next.

The so-called JavaScript compilation means that when CoffeeScript and TypeScript do not implement their own runtime, they are all compiled into equivalent JavaScript code and then run on the JavaScript interpreter.

CoffeeScript

Simplicity

CoffeeScript is a concise expression. The following code is extracted from CoffeeScript Chinese:

# Assignment: number = 42 opposite = true # condition: number =-42 if opposite # function: square = (x)-> x * x # array: list = [1, 2, 3, 4, 5] # object: math = root: Math. sqrt square: square cube: (x)-> x * square x # Splats: race = (winner, runners ...) -> print winner, runners # existence: alert "I knew it! "If elvis? # Array derivation (comprehensions): cubes = (math. cube num for num in list)

The above code is compiled into equivalent JavaScript code:

var cubes, list, math, num, number, opposite, race, square, __slice = [].slice;number = 42;opposite = true;if (opposite) { number = -42;}square = function(x) { return x * x;};list = [1, 2, 3, 4, 5];math = { root: Math.sqrt, square: square, cube: function(x) {  return x * square(x); }};race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; return print(winner, runners);};if (typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!");}cubes = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) {  num = list[_i];  _results.push(math.cube(num)); } return _results;})();run: cubes

CoffeeScript strives to be concise. Its conciseness is first manifested in the removal of some symbols only used for syntax control. These include:

Remove semicolon

Cancel var Declaration

Removes the inner code enclosed by braces and replaces it with indentation.

Function calls can omit brackets without ambiguity.

The var declaration involves complex and sophisticated JavaScript variable scope mechanisms. This part of content will not be mentioned first. CoffeeScript simplifies the problem by completely canceling the var declaration mechanism. In short, in the CoffeeScript world, variables are directly used without prior declaration. In addition, there is almost no danger in this usage.

In CoffeeScript, indentation not only beautify the code, but also represents the organization of the Code hierarchy and has a special meaning. Simply put, it is not applicable to the inner code surrounded by braces, but the inner code should be indented. Different indentation represents different code levels. The format is consistent with the content.

Indentation example:

# If indent if true 'true' else 'false' # while indent while true 'true' # function indent (n)-> n * n # object literal indent kids = brother: name: "Max" age: 11 sister: name: "Ida" age: 9

Function calls of CoffeeScript can omit parentheses without ambiguity. For example, console. log (object) can be simplified to console. log object. An example of ambiguity is that, without parameters, console. log does not know whether to retrieve the function-type attribute log or call the function log.

The function expressions of CoffeeScript are also simplified and streamlined. A single-row function can be defined as follows:

square = (x) -> x * x

Multi-row functions are organized by indentation. An empty function is the most concise:->.

This Concise Expression of the function makes it very convenient to pass the callback function. The map of an array may be enough like this:

list = [1, 2, 3]list.map (e) -> e+1

The equivalent JavaScript code cannot be so sloppy:

list = [1, 2, 3];list.map(function(e) { return e + 1; });

Enhanced expression

CoffeeScript provides some powerful expression syntaxes not available in JavaScript, which is also known as syntactic sugar. In my impression, there are many such enhancements. I will give two representative examples:

String Interpolation

List Parsing

The string interpolation method is an extension of the existing string capabilities and a simplified syntax. List parsing involves conceptual changes. The former is an improvement, while the latter is a change.

String Interpolation

In the string of CoffeeScript, you can use #{...} Embed an expression. For example:

"# {22/7} is a decent approximation of π"

It is equivalent:

"" + (22/7) + "is a decent approximation of π ";

Interpolation plays a placeholder role here, making it easier to construct strings of dynamic content. I think everyone can accept this expression.

List Parsing

List Parsing is an important member in the CoffeeScript world. It changes the idea of loop. CoffeeScript does not provide a for loop structure like JavaScript, but converts all to list parsing. A general JavaScript for Loop, as shown below:

food_list = ['toast', 'cheese', 'wine'];for (i = 0, len = food_list.length; i < len; i++) { food = food_list[i]; eat(food);}

Implementation with CoffeeScript is:

Food_list = ['toast ', 'chees', 'wine']
Eat food for food in food_list # Make a small supplement to write a single statement for a for Loop

The above example alone is not enough to show the powerful list resolution (but it is concise ). Before continuing on this topic, I think it is necessary for me to add another thing that involves the CoffeeScript concept: Everything is an expression.

In the CoffeeScript world, all statements are expression statements and return a value. Function call returns the value of the last statement by default. If condition structure also returns the value of the last statement executed. The loop structure is somewhat different. It stores the results of each loop in an array as the value of this loop structure. For example, the list result of the following code is [5, 4, 3, 2, 1].

num = 6list = while num -= 1 num

Return to the topic of list resolution. Like while, the for structure is also a loop expression and the result is an array. Return to the previous example. The list result of the following small code is ['T', 'C', 'w'].

food_list = ['toast', 'cheese', 'wine']list = (food[0] for food in food_list)

We have seen the each form of the for loop.

eat food for food in food_list

And its map form

(food[0] for food in food_list)

The filter format is given below.

(food for food in food_list when food is 'wine')

The special feature of list resolution is that it changes the way we organize loops and the way we parse arrays. This is a declarative programming method that tells the program what you want without worrying about the build process.

Class Support

Class is an important supplement of CoffeeScript to JavaScript. The prototype of JavaScript is powerful, and it is difficult to write. Setting the prototype chain correctly to implement the inheritance relationship is also a big challenge. CoffeeScript directly supports class definition in syntax, and naturally hides details.

class Animal constructor: (@name) -> move: (meters) ->  alert @name + " moved #{meters}m."class Snake extends Animal move: ->  alert "Slithering..."  super 5class Horse extends Animal move: ->  alert "Galloping..."  super 45sam = new Snake "Sammy the Python"tom = new Horse "Tommy the Palomino"sam.move()tom.move()

In terms of implementation, there is no difference between the CoffeeScript class and the JavaScript constructor and prototype chain. Therefore, understanding the prototype mechanism is also the basis for understanding the CoffeeScript class.

The dregs of JavaScript

Another goal of CoffeeScript is to directly eliminate some of the disadvantages of JavaScript at the syntax level. The semicolon section has been mentioned earlier. About the var declaration. The mechanism of semicolons is not a regular meeting for the moment. In short, there is no need to write semicolons in CoffeeScript.

In JavaScript, there are two worst-off parts, because they are used most often and are prone to errors.

Global Variables

Equal comparison

Global Variables

JavaScript's scope rules are complex, involving the var declaration mechanism and variable escalation. In JavaScript, it is easy to construct a global variable in three ways:

Use var declaration in a global environment

var name = 'name';

Define the function by omitting var.

function foo() {  name = 'name';}

Properties bound to window

Window. name = 'name ';

Among them, 1st and 2nd are the most common errors. First, we do not recommend that you encode the Code directly in the global environment. Instead, we should wrap it in an anonymous function to restrict the scope of the program to this anonymous function. The second method is to completely forget the var declaration. In actual JavaScript code, I often forget the var Declaration (just as I often forget to add a semicolon at the end of a line ).

There is no such worry in CoffeeScript. First, the compiled JavaScript code is not exposed to the global environment. All the code is automatically wrapped in an anonymous function. Then, the var declaration is automatically added to all variables. This makes it difficult to accidentally pollute the global environment unless you assign a value to the window.

Equal comparison

We all know that JavaScript has two comparison operators: = and =. We also know that = is very difficult to use, so we usually prefer to use = for a single character. CoffeeScript only has one comparison operator =, which is compiled into JavaScript =, so as to avoid this pitfall.

Whether to use CoffeeScript

CoffeeScript simplifies and enhances JavaScript expression capabilities, and avoids JavaScript pitfalls at the syntax level as much as possible. Writing code with it makes people feel clearer and comfortable, and it is not easy to make mistakes. CoffeeScript is designed to provide better JavaScript.

However, CoffeeScript is incompatible with JavaScript. It is neither a subset of JavaScript nor a superset, but a language with a clearly different idea from JavaScript. To use CoffeeScript for programming, you must change the concept. Although this idea is better and more natural, it is the main reason why some self-styled people are discouraged.

CoffeeScript is not suitable for everyone. Some people cannot accept code layers by indentation, nor can they use arrow function expressions. For them, the organization that removes the function keyword and braces is not pleasing to the eye.

List resolution is powerful, but it seems too concise. People who are used to constructing redundant JavaScript programs are not used to this expression.

In short, it is impossible to force others to learn to use CoffeeScript. JavaScript is powerful enough. You can use JavaScript to complete your work with caution. We should also encourage those who want to try CoffeeScript. They are the warriors who want to change. CoffeeScript is really worth a try, and it is really small, it is not difficult to grasp it completely.

I personally have a conservative opinion on launching CoffeeScript in the team. It would be nice if the team was using CoffeeScript from the very beginning. If you want to convert CoffeeScript to JavaScript, proceed with caution. One feasible method is to first try using CoffeeScrip in a small project to see how it works.

For individuals, there is no limit. If you really like it, try it. You can use CoffeeScript to write scripts, build your own website, and make some gadgets.

The above content is a small Editor to introduce you to the use of CoffeeScrip beautiful way to write javascript code, I hope you like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.