Skip to content

箭头函数的一个坑

LYF edited this page Jul 26, 2016 · 6 revisions

MDN关于箭头函数的说明:箭头函数就是个简写形式的函数表达式,并且它拥有词法作用域的this值(即不会新产生自己作用域下的this, arguments, super 和 new.target 等对象)。此外,箭头函数总是匿名的。)

class DB{

   constructor(size){
      this.size = parseInt(size) || 20;
   }

   query(sql,con){

       con.query(sql,() => {
            
            // 在箭头函数内部使用arguments,是它的父作用域的arguments。。
            // 箭头函数不会产生自己的this值和arguments对象
            console.log(arguments); // ['0':sql,'1':connection]          

       })
   
   }

}

使用箭头函数时,若箭头函数中用到了this时,要特别注意:

var arr = [1,2,3,4];

arr._name = '李彦峰';

// 指定forEach的第二个参数为arr。若不指定,在callback中this指向全局
arr.forEach(function(v,i){
  console.log(this._name); // 李彦峰 x 4 times
}, arr)

// 指定forEach的第二个参数为arr,但是this还是指向全局,第二个参数相当于没有
arr.forEach((v, i) => console.log(this._name), arr); // undefined x 4 times
Clone this wiki locally