122
124

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アロー関数の個人的なハマりどころまとめ

Last updated at Posted at 2016-01-17

アロー関数

  • いくつかハマりどころがあったのでメモっておく
  • 便利だけどスコープ関連ではまるのでes5の構文と混ぜるな危険というのがわかった
  • アロー関数使うときはes5を忘れましょう

構文例

es5
var f0 = function(x){ return x * 2 }
es6
const f1 = (x) => { return x * 2 }
const f2 = (x) => x * 2
const f3 = x => x * 2

thisスコープ

  • クロージャではthisが呼び出し先のthisに切り替わる仕様だったが呼び出し元のthisであることが保証された
es5
var C = function(){
    this.flag = false
}
C.prototype.asyncGet = function(callback){
    var self = this
    setTimeout(function(){
      callback(self)
    }, 1000)
}
new C().asyncGet(console.log);
es6
var C = function(){
    this.flag = false
};
C.prototype.asyncGet = function(callback){
    setTimeout(()=>callback(this), 1000)
}
new C().asyncGet(console.log)

混ぜるな危険パターン

  • プロトタイプベースのクラス定義のときにアロー関数使うとthisがグローバルを指します
es6
var C = function(){
    this.flag = false
};
C.prototype.asyncGet = (callback) => {
    setTimeout(()=>callback(this), 1000)
}
new C().asyncGet(console.log)

可変引数

es5
var f = function(){ return [].slice.call(arguments) }
f(1,2,3,4,5,6,7,8,9)
[1,2,3,4,5,6,7,8,9]
es6
const f = (...args) => args
f(1,2,3,4,5,6,7,8,9)
[1,2,3,4,5,6,7,8,9]

混ぜるな危険パターン

  • argumentsがグローバルスコープを指しているため、かならず意図しない配列が返ってきます
  • es5からes6へ書き換えるときにおきます
es6
const f = () => [].slice.call(arguments)
f(1,2,3,4,5,6,7,8,9)
[{},
{ [Function: require]
    resolve: [Function],
    main: 
  ....
]
122
124
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
122
124

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?