一、 特性一览
- 异步语法支持
- Ruby Symbol语法的字串
- 正则运算符 =~
- 正则Magic标识符 \& \~ \1..9
1. 异步语法支持
语法: 在调用的函数尾加上!(感叹号)输入:
do ->
# ! always is a function
foo_0_0!
@va = obj.foo_2_1! 'pa', 'pb'
# @ is inherited
[va, @vb] = obj::foo_2_2! 'pa', 'pb'
# another async block
do ->
@va = @foo! 'pa'
# if, while and so on has block too
if true
va = foo!
else
vb = foo!
var _this = this;
(function() {
var _this = this;
return foo_0_0(function() {
return obj.foo_2_1('pa', 'pb', function(va) {
_this.va = va;
return obj.prototype.foo_2_2('pa', 'pb', function(va, vb) {
_this.vb = vb;
});
});
});
})();
(function() {
var _this = this;
return this.foo('pa', function(va) {
_this.va = va;
});
})();
if (true) {
foo(function(va) {});
} else {
foo(function(vb) {});
}
a. 原理
ToffeeScript 会把
[any expression] = foo!(params)
other expression
foo params, (any expression) =>
other expression
[a = '3', @b = '4'] = foo!
@a = foo!
...
等等
2. Symbol语法的字串
ToffeeScript引用了Ruby Symbol的语法,但本质仍是字串,可以看成一种字串的便捷写法。语法: 以:开头的字串 /^\:((?:\\.|\w|-)+)/
备注: - 是有效的字串部份,
输入:
:hello_world
:hello-world
'hello_world'
'hello-world'
3. 正则运算符 =~
语法: 字串 =~ 正则表达式输入:
"hello" =~ /\w+/
var __matches = null;
__matches = "hello".match(/\w+/);
4. 正则Magic标识符 \& \~ \1..9
Magic标识符:
\~: the match
\&: match[0]
\1: match[1]
\2: match[2]
...
\9: match[9]
if :hello =~ /^\w+$/
console.info :matched
if :333-444 =~ /^(\d+)-(\d+)$/
console.info \1, \2
(function() {
var __matches = null;
if (__matches = 'hello'.match(/^\w+$/)) console.info('matched');
if (__matches = '333-444'.match(/^(\d+)-(\d+)$/)) {
console.info(__matches[1], __matches[2]);
}
}).call(this);
二、 安装
npm install -g toffee-script
三、 相关链接
ToffeeScript GithubCoffeeScript Github
COffeeScript 语法介绍