var, let, const , arguments , 箭头函数 - archering/basic GitHub Wiki

“var” are processed at the function start ; var 定义前置,“hoisting”

“var” has no block scope ; var 是函数作用域或者全局作用域

es6之前的block ,{ } 之间的部分是没有作用域的,或者说没有 lexical Environment的 in JavaScript blocks had no Lexical Environments

ES6 引入 let , const 之后就有了 block scope 也就有了 bock 级的 lexical Environment


Arrow functions have no “this” ; 很简单的理解这句话,就是无this

举例说明,以前我们这样写程序, forEach 里面的function 里面的this (函数作用域) 已经不是外部的group了

let group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],

  showList() {
    this.students.forEach(function(student) {
      // Error: Cannot read property 'title' of undefined
      alert(this.title + ': ' + student)
    });
  }
};

group.showList();

换成箭头函数,no pros

let group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],

  showList() {
    this.students.forEach(
      student => alert(this.title + ': ' + student)  //没有问题,this就是group 
    );
  }
};

group.showList();

引文没有this, Arrow functions can’t run with new

a regular function called with .bind(this): 原方式定义的函数有一个 bind 方法可以用来给function指定this上下文

.bind(this) creates a “bound version” of the function.

The arrow => doesn’t create any binding. The function simply doesn’t have this. The lookup of this is made exactly the same way as a regular variable search: in the outer lexical environment.

重点在最后一句话,箭头函数内部如果用到了this, 那么他会向找变量一样顺着lexicol environment 来找。