以前也写过一些前端,比如我自己的博客,就是用 JQuery+HTML+CSS 实现的,但是大部分都是抄的,特别是 CSS 样式,真让人头大。至于 JS 部分,也是现学现撸,很不成体系,更不用说更深入的语言细节了,那就是一塌糊涂。
最近浏览博客,发现之前关注的博主 miguelgrinberg.com 开始在写 React 的教程,所以打算跟进学习一下,正好了解一下现代的 JS 框架是怎么样的,学习下前端工程是怎么构建的。
听说成为全栈工程师能更容易拿到远程工作的 offer,嗯不错不错,开始搞吧,学习使我快乐~
教程地址:Introducing the React Mega-Tutorial
我会在博客里记录一下有意思和对我来说重要的点,主要就是个笔记吧。
ES5 vs. ES6
ECMA, ECMAScript
transpiling:which converts modern JavaScript source code into functionally equivalent ES5 code that runs everywhere.
Summary of Recent JavaScript Features
Trailing Commas
很有帮助的观点:
1 2 3 4 5
| const myArray = [ 1, 3, 5, ];
|
在最后面一个元素加上逗号有两点好处,一个是上下挪动比较方便,另一个是新加元素比较方便。
Imports and Exports
这里其实没有完全理解,default export到底和其他export有什么意思,文中说了一句话:When using default exports, the name of the exported symbol does not really matter.
后面举的例子,说 import myReallyCoolFunction from './cool';
也是有效的,那和 import myCoolFunction from './cool';
是一个意思?
也就是说 default export 的东西,因为一个模块只能有一个,所以在其他模块引用的时候可以随便用任何名字?
先保留这个疑惑,继续往下看。
另外导入 non-default export 也有一点不一样,需要加大括号 import { SQRT2 } from './cool';
Variables and Constants
使用 let 来声明变量,const 来声明常量。
常量就是赋值之后不能有新的赋值了,而且也必须是在声明的时候赋值。
Equality and Inequality Comparisons
===
和 !==
String Interpolation
1 2
| const name = 'susan'; let greeting = `Hello, ${name}!`;
|
For-Of Loops
1 2 3 4
| const allTheNames = ['susan', 'john', 'alice']; for (name of allTheNames) { console.log(name); }
|
Arrow Functions
之前 code review 的时候看过这种写法,觉得很神秘,现在详细了解之后,其实也没啥,正如 Python 里的匿名函数,lambda 表达式一样。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| function mult(x, y) { const result = x * y; return result; }
const mult = (x, y) => { const result = x * y; return result; };
const mult = (x, y) => x * y;
const square = x => x * x;
longTask(result => console.log(result));
|
在 Python 里就会这么写
Promises
1 2 3 4
| fetch('http://example.com/data.json') .then(r => r.json()) .then(data => console.log(data)) .catch(error => console.log(`Error: ${error}`));
|
Async and Await
上面的写法可以改成这样,更易读
1 2 3 4 5
| async function f() { const r = await fetch('https://example.com/data.json'); const data = await r.json(); console.log(data); }
|
加上 async 的函数会自动返回一个 promise
箭头函数也可以使用 async
1 2 3 4
| const g = async () => { await f(); console.log('done!'); };
|
Spread Operator