esa*_*wan 2 javascript sorting ecmascript-6 arrow-functions
我一直试图了解es6箭头功能.我读了一些介绍它的文章.但我仍然没有完全得到它.
例如,我有这个代码:
sortedArticles(): Article[] {
return this.articles.sort((a: Article, b: Article) => b.votes - a.votes);
}
Run Code Online (Sandbox Code Playgroud)
它对下面的数组进行排序:
[
new Article('Angular 2', 'http://angular.io', 3),
new Article('Fullstack', 'http://fullstack.io', 2),
new Article('Angular Homepage', 'http://angular.io', 1),
];
Run Code Online (Sandbox Code Playgroud)
如何在普通的旧js中看到相同的代码?我无法完全得到它.
如果您刚刚将箭头函数转换为函数,它将如下所示function:
sortedArticles(): Article[] {
return this.articles.sort(function(a: Article, b: Article) { return b.votes - a.votes;});
// ---------------------------^^^^^^^^------------------------^^^-------------------------^^
}
Run Code Online (Sandbox Code Playgroud)
...但请注意,那里比ES2015("ES6")更多.该: Article[]部分是说sortedArticles返回一个数组Article.(同样的: Article限定符a和b.)这根本不是JavaScript.它看起来像TypeScript.
纯JavaScript版本只会删除那些类型注释:
sortedArticles() {
return this.articles.sort(function(a, b) { return b.votes - a.votes;});
}
Run Code Online (Sandbox Code Playgroud)
但TypeScript的"胖箭"功能与ES2015的箭头功能大致相同,所以让我们继续讨论ES2015箭头功能:
箭头功能和功能之间有四个基本区别1function:
他们关闭了this,super以及其他几件事,2他们没有像function函数那样的自己的版本.(这样做的结果是,super如果它们在可以使用的上下文中定义,它们可以使用super,哪些function函数不能.)
他们可以有一个简洁的身体,而不是一个冗长的身体(但他们也可以有一个冗长的身体).
它们不能用作构造函数.例如,您不能使用new箭头功能.这样做的结果是箭头函数没有prototype属性(因为它仅在与函数一起使用时才使用new).
箭头函数没有生成器语法.例如,没有相当于的箭头function *foo() { ... }.
这三个函数实际上都是相同的,因为它们不使用this或arguments:
// A `function` function
var f1 = function(x) {
return x * 2;
};
// An arrow function with a verbose body
var f2 = x => {
return x * 2;
};
// An arrow function with a concise body
var f3 = x => x * 2;
Run Code Online (Sandbox Code Playgroud)
(如果他们使用this或者arguments,他们就不一样了.)
请注意,简洁的主体{后面没有,=>并且必须包含单个顶级表达式(当然可以有子表达式),它用作返回值.
1你会发现人们告诉你的是第五个:箭头功能不能有名字.这是一个神话.箭头功能可以有名称; 上面的箭头功能有真正的名字,f2并f3分别.它不仅仅是具有名称的变量,而且功能也是如此.
2具体而言,它们可以关上 this,super,arguments(的运行时参数自动伪阵列),和new.target.
非常感谢CodingIntrigue指出了本答案早期版本中的几个错误和遗漏.
| 归档时间: |
|
| 查看次数: |
1775 次 |
| 最近记录: |