JavaScript is undoubtedly one of the greatest inventions on the web, and almost all the dynamic effects of Web pages are based on its rich computational power. And its capabilities are getting stronger under the Engine of a variety of new JavaScript, such as Google Chrome's V8 Engine.
However, due to the birth of too early, there are many grammatical definitions today seems to be somewhat inefficient, some more advanced grammatical forms, for historical reasons, no way to join the current JavaScript language, can say a regret.
Many of the world's geniuses are trying to build better JavaScript. There have been many attempts, the most promising of which is coffeescript and typescript. In the face of Coffeescript, I have hit feeling, and typescript also aroused my great interest. Coffeescript, like Typescript, are languages that are compiled into JavaScript, all of which enhance JavaScript's expressive power. This article is about Coffeescript, and Typescript will put it in the next article.
Compiling as JavaScript means that coffeescript and typescript do not implement their own run-time, they are compiled into equivalent JavaScript code and then run on the JavaScript interpreter.
Coffeescript
Simple nature
Coffeescript gives the biggest impression is its concise expression. The following code I extracted from the Coffeescript Chinese:
# Assignment: number =
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:< c16/> (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 the equivalent JavaScript code:
var cubes, list, math, num, number, opposite, race, square,
__slice = [].slice;
Number = N;
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 strive to be concise. Its simplicity first manifests itself in the removal of some symbols that are used only for grammatical control. This includes:
Cancel Semicolon
Cancel Var declaration
Remove braces to surround inner code and replace with indents
function calls can omit parentheses without ambiguity
The Var declaration involves a complex and very chicken-scoped JavaScript variable scope mechanism. This part of the content is not to speak first. Coffeescript simplifies the problem by completely canceling the Var declaration mechanism. In short, in the Coffeescript world, variables need not be stated in advance, just use them. And this usage is basically nothing dangerous.
Indentation in the coffeescript is not only to beautify the code, it represents the code level of the organization, there is a special meaning. Simply put, the braces surround the inner code, but the inner code is indented. Different indents represent different levels of code. The form and content are consistent.
Examples of indents:
#if缩进
If True '
true '
else
' false '
#while缩进 while
true
' true '
#函数缩进
(n)->
n * N
#对象字面量缩进
kids =
Brother:
Name: "Max"
age:11
sister:
name: "Ida"
In the absence of ambiguity, coffeescript function calls can omit parentheses. For example, Console.log (object) can be simplified to console.log object. One example of ambiguity is the absence of parameters, Console.log does not know whether to remove the function-type property log or call function log.
Coffeescript's function expression has also done the ultimate streamlining and streamlining. A single line function can be defined as this:
Multiline functions are also organized by indenting. An empty function is the most concise, so:->.
This concise expression of the function makes it very convenient to pass the callback function. A map of an array might be enough like this:
list = [1, 2, 3]
List.map (e)-> e+1
The equivalent JavaScript code is not so sloppy:
list = [1, 2, 3];
List.map (function (e) {return e + 1;});
Enhanced expression
Coffeescript provides some powerful expression syntax that JavaScript does not have, which is what is called the grammatical candy. In my impression, this kind of enhancement is many, I cite two representative examples:
String interpolation method
List resolution
The string interpolation method is an extension of the existing string capabilities and a syntactic simplification, and list parsing involves conceptual changes. The former is an improvement, and the latter is a change.
String interpolation method
In the Coffeescript string, you can use #{...} Embed an expression. For example:
"#{22/7} is a decent approximation ofπ"
Equivalent to:
"" + (22/7) + "is a decent approximation ofπ";
Interpolation plays a role in placeholder, making it easier to build strings for dynamic content. I think everyone can accept this expression.
List resolution
List parsing is an important part of the Coffeescript world. It changes the way the cycle is thought. Instead of providing a for-loop structure like JavaScript, Coffeescript is transformed into list parsing. A regular javascript for loop, like the following:
Food_list = [' toast ', ' cheese ', ' wine '];
for (i = 0, len = food_list.length i < len; i++) {
food = food_list[i];
Eat (food);
}
Using Coffeescript to achieve is:
Food_list = [' toast ', ' cheese ', ' wine ']
Eat food for food in Food_list #做个小补充, the writing of a single statement for the loop
The above example alone is not enough to show the strength of the list resolution (see its simplicity). Before continuing this topic, I think I need to add another thing that involves the coffeescript idea: everything is an expression.
In the Coffeescript world, all statements are expression statements, and all return a value. The function call returns the value of the last statement by default. The IF condition structure also returns a value that returns the value of the last statement executed. The loop structure is somewhat different, and it saves the results of each loop in an array as the value of this loop structure. For example, the list result for the following code is [5, 4, 3, 2, 1].
num = 6
list = while num = 1
num
Return to the topic of the list resolution. As a while, the for structure is a circular expression, and the result is an array. Back 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've seen 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 form is given below
(Food for food in food_list when food is ' wine ')
The feature of list parsing is that it changes the way we organize our loops and parse the pattern of arrays. This is a declarative programming method that tells the program what you want without caring about the build process.
Support for classes
Class is an important complement to JavaScript in Coffeescript. JavaScript's prototype is powerful, and it's a very awkward style. Setting up the prototype chain correctly to implement the inheritance relationship is also a big challenge. Coffeescript directly supports the definition of the class from the syntax, and hides the details naturally.
Class Animal
constructor: (@name)-> move
: (meters)->
alert @name + "moved #{meters}m."
Class Snake extends Animal move
:->
alert "slithering ..."
Super 5
class horse
extends Move:->
Alert "galloping"
super
Sam = new Snake "Sammy the Python"
tom = new horse "Tommy th" E Palomino "
sam.move ()
tom.move ()
From the implementation point of view, the Coffeescript class is not the same as the JavaScript constructor and the prototype chain. Therefore, understanding the prototype mechanism is also the basis for understanding the Coffeescript class.
About the dross of JavaScript
Another goal of Coffeescript is to eliminate some of the most reviled parts of JavaScript from the grammatical level. The part about the semicolon has been mentioned earlier. Part about the Var declaration. The semicolon mechanism will not go to the regular meeting, in short coffeescript do not have to write a semicolon.
In JavaScript, the most reviled parts of the dross are two, because they use the most common and error-prone situations.
Global variables
Equality comparisons
Global variables
JavaScript's scoping rules are complex, involving VAR declaration mechanisms and variable elevation. In JavaScript, it's easy to construct a global variable in three ways:
Using Var to declare in a global environment
Defined in a function by omitting Var
function foo () {
name = ' name ';
}
Properties bound to Window
Window.name = ' name ';
The 1th and 2nd methods are the most common error usage. Coding directly in the global environment is not recommended first, but should be wrapped with an anonymous function that restricts the scope of the program to this anonymous function. The second usage is completely oblivious to the Var declaration. And I'm in the actual JavaScript code, forget the Var declaration is often the case (like often forget the end of the line to make up a semicolon).
And in the coffeescript there is no such worry at all. First, the compiled JavaScript code is not exposed to the global environment, and all code is automatically wrapped in an anonymous function (function () {...}) (); All variables are then automatically added to the Var declaration. This makes it very difficult to pollute the global situation accidentally unless you use assignment to Windows.
Equality comparisons
We all know that JavaScript has two comparison operators: = = and = =. We also know that = = in the use of the process will be very pit, so usually prefer to play one more character and use = =. Coffeescript has only one comparison operator = =, which is compiled into javascript = = =, which is a good way to circumvent this pit.
Whether to use the Coffeescript
Coffeescript simplifies and enhances JavaScript's expressive power, avoiding some of the javascript holes from the grammar level as much as possible. Writing code with it makes people feel clearer and more comfortable, and it's not easy to make mistakes. Coffeescript's original intention was to provide better JavaScript.
However, Coffeescript is incompatible with JavaScript. It is neither a subset of JavaScript nor a superset, but a language with apparently different ideas from JavaScript. To use Coffeescript programming is necessarily to change the concept, although this idea is better and more natural, but it is a few people who are not deterred by the main reason.
Coffeescript is not for everyone. Some people do not accept the use of the arrow function to accept the level of the indent organization code. For them, removing the function keywords and braces is not pleasing to the eye of the Organization.
The list parsing is powerful, but it's also too concise. For those who are accustomed to constructing miscellaneous JavaScript programs, they are not accustomed to this expression.
In short, is not forced to learn to use Coffeescript. JavaScript is already strong enough to work well with JavaScript as long as you're careful enough to do it. For those who want to try to coffeescript, we should also give encouragement to the attitude, they are the Warriors of novelty and change. Coffeescript is really worth a try, and it's really small and it's not difficult to master it completely.
I also hold a conservative view on the implementation of Coffeescript in the team. If the team is using coffeescript from the start it's okay. If you want to switch from Coffeescript to JavaScript, you should do it carefully. One possible way is to try to use Coffeescrip in a small project to see how it works.
For an individual, there is no limit. If you really like it, try it. You can use Coffeescript to write scripts, build your own web site, and do some gadgets.
The above content is a small series to introduce you to use Coffeescrip graceful way to write JavaScript code, I hope you like.