Home > Web Front-end > JS Tutorial > body text

Use CoffeeScrip to write javascript code in a beautiful way_javascript tips

WBOY
Release: 2016-05-16 15:34:44
Original
1232 people have browsed it

JavaScript is undoubtedly one of the greatest inventions on the web. Almost all dynamic effects on web pages are based on its rich computing power. And its capabilities are becoming more and more powerful with various new JavaScript engines, such as the V8 Engine used by Google Chrome.

However, because it was born too early, many grammatical definitions are somewhat inefficient today. Some more advanced grammatical forms cannot be added to the current JavaScript language due to historical reasons, which can be said to be a pity.

A lot of geniuses around the world are working hard to build better JavaScript. There have been many attempts, the most promising of which are nothing more than CoffeeScript and TypeScript. Facing CoffeeScript, I felt like old friends at first sight; and TypeScript also aroused my great interest. CoffeeScript, like TypeScript, is a language compiled into JavaScript, and they both enhance the expressive capabilities of JavaScript. This article is about CoffeeScript, TypeScript will be discussed in the next article.

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

CoffeeScript

Simplicity

The biggest impression of CoffeeScript is its concise expression. The following code is excerpted from CoffeeScript Chinese:

# 赋值:
number  = 42
opposite = true
# 条件:
number = -42 if opposite
# 函数:
square = (x) -> x * x
# 数组:
list = [1, 2, 3, 4, 5]
# 对象:
math =
 root:  Math.sqrt
 square: square
 cube:  (x) -> x * square x
# Splats:
race = (winner, runners...) ->
 print winner, runners
# 存在性:
alert "I knew it!" if elvis?
# 数组 推导(comprehensions):
cubes = (math.cube num for num in list)

Copy after login

The above code will compile to the 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 &#63; __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
Copy after login

CoffeeScript strives for simplicity. Its simplicity is first reflected in the removal of some symbols that are only used for syntax control. These include:

Cancel semicolon

Cancel var declaration

Cancel the braces surrounding the inner code and use indentation instead

Function calls can omit parentheses if there is no ambiguity

The var declaration involves the complicated and useless JavaScript variable scope mechanism. Let’s leave this part of the story aside for now. CoffeeScript simplifies the problem by completely eliminating the var declaration mechanism. In short, in the CoffeeScript world, variables do not need to be declared in advance, just use them directly. And there is basically no danger in this usage.

Indentation in CoffeeScript is not only used to beautify the code, but also represents the organization of the code level, which has a special meaning. To put it simply, the inner code should not be surrounded by braces, but the inner code should be indented. Different indentations represent different code levels. Form and content are consistent.

Example of indentation:

#if缩进
if true
 'true'
else
 'false'
#while缩进
while true
 'true'
#函数缩进
(n) ->
 n * n
#对象字面量缩进
kids =
 brother:
  name: "Max"
  age: 11
 sister:
  name: "Ida"
  age: 9 
Copy after login

CoffeeScript function calls can omit parentheses without causing ambiguity. For example, console.log(object) can be simplified to console.log object. An example of ambiguity is that in the absence of parameters, console.log does not know whether to take out the functional attribute log or call the function log.

CoffeeScript’s function expressions have also been extremely streamlined and streamlined. A one-line function definition can look like this:

square = (x) -> x * x
Copy after login

Multi-line functions are also organized through indentation. An empty function is the most concise, like this: ->.

This concise expression of functions makes passing callback functions very convenient. A map of the array might suffice like this:

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

The equivalent JavaScript code cannot be so sloppy:

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

Enhanced Expression

CoffeeScript provides some powerful expression syntax that JavaScript does not have, which is also called syntactic sugar. In my mind, there are many such enhancements. I will give you two representative examples:

String Interpolation

List parsing

The string interpolation method is an expansion and grammatical simplification of the existing string capabilities; while list parsing involves a change in concept. The former is an improvement, the latter is a change.

String Interpolation

In CoffeeScript strings, you can use #{…} to embed an expression. For example:

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

is equivalent to:

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

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

List parsing

List comprehensions are an important player in the world of CoffeeScript. It changes the way the cycle is thought about. CoffeeScript does not provide a for loop structure like JavaScript, but all is converted into list analysis. A regular JavaScript for loop, like this:

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

用CoffeeScript实现就是:

food_list = ['toast', 'cheese', 'wine']
eat food for food in food_list #做个小补充,for循环的单条语句的写法

单单是上面的例子不足以显示列表解析的强大(却看到它的简洁了)。在继续这个话题之前,我觉得我有必要补充一下另一个涉及到CoffeeScript理念的东西了:一切皆是表达式。

在CoffeeScript世界里,一切语句都是表达式语句,都会返回一个值。函数调用默认会返回最后一条语句的值。if条件结构也会返回值,其返回的是执行的最后一条语句的值。循环结构有些不同,其会将每次循环的结果都保存在一个数组里,作为此循环结构的值。例如下面代码的list结果就是[5, 4, 3, 2, 1]。

num = 6
list = while num -= 1
 num
Copy after login

回到列表解析的主题。与while一样,for结构也是一种循环的表达,其结果也是一个数组。回到先前的例子,下面的小代码的list结果就是['t', 'c', 'w']。

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

我们已经看到for循环的each形式

eat food for food in food_list
Copy after login

以及它的map形式

(food[0] for food in food_list)
Copy after login

下面给出它的filter形式

(food for food in food_list when food is 'wine')
Copy after login

列表解析的特色的地方在于它改变了我们组织循环的方式和解析数组的模式。这是一种声明式的编程方法,告诉程序你想要什么而不去关心构建的过程。

类的支持

类是CoffeeScript对JavaScript的一个很重要的补充。JavaScript的原型功能很强大,写法上又恨别扭。正确地设置原型链以实现继承关系也是个很大的挑战。CoffeeScript从语法上直接支持类的定义,自然且隐藏细节。

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

从实现上来说,CoffeeScript的类与JavaScript的构造函数和原型链那一套并无二致。所以,理解原型机制也是理解CoffeeScript类的基础。

关于JavaScript的糟粕

CoffeeScript的另一个目标是从语法层面上直接消除JavaScript的被人诟病的一些糟粕部分。前面已经说过关于分号的部分。关于var声明的部分。分号的机制暂且不去例会,总之CoffeeScript不用再去写分号了。

在JavaScript当中,最为人诟病的糟粕部分有两处,因为它们使用的情况最多而且容易出错。

全局变量

相等比较

全局变量

JavaScript的作用域规则很复杂,涉及到var声明机制和变量提升。在JavaScript里,构造一个全局变量是很容易的,有三种方式:

在全局的环境里用var声明

var name = 'name';
Copy after login

在函数内用省略var的方式定义

function foo() {
  name = 'name';
}
Copy after login

Attributes bound to window

window.name = 'name';

The first and second methods are the most common incorrect usages. First of all, it is not recommended to code directly in the global environment. Instead, it should be wrapped in an anonymous function to limit the scope of the program to this anonymous function. The second usage is to completely forget the var declaration. In actual JavaScript coding, it is common for me to forget the var declaration (just like I often forget to add a semicolon at the end of the line).

In CoffeeScript, there is no such worry at all. First of all, the compiled JavaScript code will not be exposed to the global environment. All code is automatically wrapped in an anonymous function (function(){ ... })();. Then, all variables will be automatically declared with var. This makes it difficult to accidentally pollute the global situation, unless you use assignment to window.

Equality comparison

We all know that JavaScript has two comparison operators: == and ===. We also know that == can be tricky to use, so we usually prefer to type one more character and use ===. CoffeeScript has only one comparison operator ==, and it will be compiled into JavaScript's ===, thus avoiding this pitfall.

Should I use CoffeeScript

CoffeeScript simplifies and enhances the expression ability of JavaScript, and avoids some pitfalls of JavaScript as much as possible from the grammatical level. Using it to write code will make people feel clearer and more comfortable, and it will be less easy to make mistakes. The original intention of CoffeeScript is to provide better JavaScript.

However, CoffeeScript is incompatible with JavaScript. It is neither a subset nor a superset of JavaScript, but a language with obviously different ideas from JavaScript. Programming with CoffeeScript requires changing concepts. Although this concept is better and more natural, it is the main reason why some people who are stuck in their ways are deterred.

CoffeeScript is not suitable for everyone. Some people simply cannot accept the use of indentation to organize code hierarchies, nor the use of arrow function expressions. For them, the organization without the function keyword and braces is not pleasing to the eye.

List parsing is very powerful, but it is also too concise. For people who are used to constructing complicated JavaScript programs, they are not used to this expression.

In short, you cannot force others to learn to use CoffeeScript. JavaScript is powerful enough that as long as you are careful enough, you can use JavaScript to get the job done well. For those who want to try CoffeeScript, we must also give an encouraging attitude. They are warriors seeking innovation and change. CoffeeScript is really worth a try, and it's really small and it's not difficult to master it completely.

I personally have a conservative view on implementing CoffeeScript in the team. It would be better if the team used CoffeeScript from the beginning. If you are switching from CoffeeScript to JavaScript, be careful. One possible way is to try using CoffeeScrip in a small project first to see how it works.

For individuals, there are no restrictions. If you really like it, go for it. You can use CoffeeScript to write scripts, build your own website, and make some gadgets.

The above content is the beautiful way to write javascript code using CoffeeScrip introduced by the editor. I hope you like it.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template