Generators & Advanced iteration

Generators

  • Can return (“yield”) multiple values, one after another, on-demand.
  • They work great with iterables, allowing to create data streams with ease.

generator functions, function*

1
2
3
4
5
function* generateSequence() {
yield 1;
yield 2;
return 3;
}
  • When it (generateSequence()) is called, it doesn’t run its code. Instead it returns a “generator object” ([object Generator]), to manage the execution.

Promises & async/await

Promise

异步操作

  • 回调函数:
    • fs 文件操作
    • 数据库操作
    • AJAX
    • 定时器
  • Promise:语法上是构造函数 / 功能上使用promise对象 封装一个异步操作并可获取成功或失败的结果值
    • 优点:
      1. 支持链式调用,解决回调地狱问题(不便于阅读+不便于异常处理)
        • .then方法返回的还是一个Promise对象
      2. 制定回调函数的方式更加灵活(旧的只能在启动异步任务前制定),但promise是先启动异步任务→返回promise对象→给promise对象绑定回调函数(甚至可以在异步任务结束后制定多个)
  • 队列任务优先级process.nextTick > promise的回调 > async > setTimeout > setInterval > setImmediate > I/O > UI rendering

Syntax

  • 封装一个异步函数 → 成功调resolve,失败调reject.then方法制定成功和失败的回调,并对结果进行处理

Prototypes / Inheritance

Prototypal inheritance

obj.__proto__ – old verison

  • to access objects’ hidden [[Protptype]] property, either another object or null.

Writing doesn’t use prototype

  • Write / delete operator work directly with the object. Not use to change the prototype.
  • The prototype is only used for reading properties

iterate properties

  • for...in loop iterates over inherited properties.
  • Object.keys() only returns own keys. (almost all key/value-getting methods)

Functions

函数定义

  • 采用function命令声明函数会提升。赋值语句定义函数不会
  • 具名函数只能在函数内部调用, 赋值后就没有意义
    • name 属性会返回具名函数 function字段后的名称
      1
      2
      var f3 = function myName() {};
      f3.name // 'myName'

函数的作用域

  • 作用域与变量一样, 就是其声明时所在的作用域,与其运行时所在的作用域无关。
  • 形成闭包现象

Classes

Class basic

syntax

1
2
3
4
5
6
7
8
9
10
class MyClass { // basically is a function
prop = value; // property, is not written to `MyClass.prototype`
constructor(...) { ... } // constructor
method(...) {} // method
get something(...) {} // getter method
set something(...) {} // setter method

[Symbol.iterator]() {} // method with computed name (symbol here)
['say' + 'Hi']() {} // `[...]` computed `sayHi()`
}

Sass

Intro to Sass

Variables $

1
2
3
4
5
6
7
$font-stack:    Helvetica, sans-serif;
$primary-color: #333;

body {
font: 100% $font-stack;
color: $primary-color;
}

Interpolation #{}

  • Interpolation is useful for injecting values into strings.

Nesting