Javascript オブジェクトは、 Ruby のハッシュのようなロケット構文では表現できない場合があります。
ただし、ECMAScript 6 が採用されると、Javascript 実装は匿名関数の定義に同じシンボルを使用できるようになりました=>
が、それらはアロー関数または口語的にはハッシュ ロケットではなくファット アローと呼ばれます。
単純な関数の場合、アロー構文による定義と従来の関数の定義に違いはありません。
var foo = function (s) { return s.toString() }
と
function foo(s) { return s.toString() }
以下と同等です。
var foo = (s) => { return s.toString() }
さらに、これらは両方とも次と同等です。
var foo = (s) => s.toString()
としても:
const foo = s => s.toString()
ただし、 を使用する場合this
は、従来の関数とアロー関数のどちらを選択するかが重要になります。従来の定義の関数は の新しいスコープを作成しますがthis
、アロー関数は作成しないためです。Mozilla ContributorsによるArrow 関数に関する Mozilla doc の例( CC-BY-SA 2.5 の 下でライセンスされています):
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
ここで、p.age
は常に 0 になります。これは、インクリメントされるは、 のインスタンスではなく、内部関数内にのみ存在する にage
属しているためです。内部関数がアロー関数として定義されている場合:this
Person
p
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(() => {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
p.age
in 内部関数はインスタンスp
の.this
this
詳細については、Mozilla ドキュメントを参照してください。