关于es6:学习ES6箭头函数

0次阅读

共计 2006 个字符,预计需要花费 6 分钟才能阅读完成。

ES6 容许应用“箭头”(=>)定义函数。

let xxx = (p1,p2)=>{console.log(1)
    return 2
}

// 只有一个参数,能够省略括号
let xxx = p1 =>{console.log(1)
    return 2
}

// 代码块只有一句话时,能够省略花括号和 return
let xxx = (p1,p2) => p1+p2
// 等同于
let xxx = function(p1,p2) {return p1 + p2;};

// 只有一个参数,代码块只有一句话时,能够省略括号、花括号和 return
let xxx = p1 => p1*2

// 如果箭头函数不须要参数或须要多个参数,就应用一个圆括号代表参数局部。let f = () => 5;
// 等同于
let f = function () { return 5};

箭头函数的一个用途是简化回调函数。

// 失常函数写法
[1,2,3].map(function (x) {return x * x;});

// 箭头函数写法
[1,2,3].map(x => x * x);

箭头函数 this 的用法

先看个 ES 3 this 的用法的例子

let obj = {
    name: 'obj',
    hi:function(p1,p2){console.log(this.name)
    }
}
obj.hi(1,2) // 等价于 obj.hi.call(obj,1,2)

能够看出 this 是 call 的第一个参数,如果不传 call,很难晓得 this 到底指向谁。

箭头函数有几个应用留神点。

(1)函数体内的 this 对象,就是定义时所在的对象,而不是应用时所在的对象。

(2)不能够当作构造函数,也就是说,不能够应用 new 命令,否则会抛出一个谬误。

(3)不能够应用 arguments 对象,该对象在函数体内不存在。如果要用,能够用 rest 参数代替。

(4)不能够应用 yield 命令,因而箭头函数不能用作 Generator 函数。

this 对象的指向是可变的,然而在箭头函数中,它是固定的。

function foo() {setTimeout(() => {console.log('id:', this.id);
  }, 100);
}

var id = 21;

foo.call({id: 42});
// id: 42

箭头函数能够让 this 指向固定化,这种个性很有利于封装回调函数。上面是一个例子,DOM 事件的回调函数封装在一个对象外面。

var handler = {
  id: '123456',

  init: function() {
    document.addEventListener('click',
      event => this.doSomething(event.type), false);
  },

  doSomething: function(type) {console.log('Handling' + type  + 'for' + this.id);
  }
};

下面代码的 init 办法中,应用了箭头函数,这导致这个箭头函数外面的 this,总是指向 handler 对象。否则,回调函数运行时,this.doSomething 这一行会报错,因为此时 this 指向 document 对象。

箭头函数转成 ES5 的代码如下。

// ES6
function foo() {setTimeout(() => {console.log('id:', this.id);
  }, 100);
}

// ES5
function foo() {
  var _this = this;

  setTimeout(function () {console.log('id:', _this.id);
  }, 100);
}

上面的代码之中有几个 this

function foo() {return () => {return () => {return () => {console.log('id:', this.id);
      };
    };
  };
}

var f = foo.call({id: 1});

var t1 = f.call({id: 2})()(); // id: 1
var t2 = f().call({id: 3})(); // id: 1
var t3 = f()().call({id: 4}); // id: 1

下面代码之中,只有一个 this,就是函数 foo 的 this,所以 t1、t2、t3 都输入同样的后果。因为所有的内层函数都是箭头函数,都没有本人的 this,它们的 this 其实都是最外层 foo 函数的 this。

除了 this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments、super、new.target。

function foo() {setTimeout(() => {console.log('args:', arguments);
  }, 100);
}

foo(2, 4, 6, 8)
// args: [2, 4, 6, 8]

下面代码中,箭头函数外部的变量 arguments,其实是函数 foo 的 arguments 变量。

另外,因为箭头函数没有本人的 this,所以当然也就不能用 call()、apply()、bind() 这些办法去扭转 this 的指向。

正文完
 0