Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

アロー関数

  • いくつかハマりどころがあったのでメモっておく
  • 便利だけどスコープ関連ではまるので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: 
  ....
]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away