JavaScriptで矢印関数を使用しない場合


矢印機能は、従来の関数式により簡潔な代替手段ですが、どこにも適切ではありません.
あなたが矢関数を使いたくない何回かの例をチェックしましょう.

シナリオ1動的なコンテキストを必要とするコールバック関数.
要素のクリックなどの動的コンテキストを必要とするコールバック関数は、定義済みのコンテキストを変更できないため、矢印関数の候補となりませんthis .
const button = document.querySelectorAll( '.cta-button' );

button.addEventListener( 'click', () => {

this.classList.toggle( 'selected' ); // `this`refers to the Window. 😔

} );
通常の関数を使用するとthis ターゲット要素のコンテキストに基づいて変更するには.
const button = document.querySelectorAll( '.cta-button' );

button.addEventListener( 'click', function() {

this.classList.toggle( 'selected' ); // `this`refers to the button! 🎉🎉🎉

} );

シナリオ2を使う関数arguments オブジェクト.
矢印関数はグローバルにバインドされませんarguments オブジェクト.
const logUser = () => {

console.log(arguments[0]); // Uncaught ReferenceError: arguments is not defined 😕

}

logUser( 'Kevin' );
しかし、通常の機能では、グローバルへのアクセスを持ってarguments オブジェクト.
function logUser() {

console.log(arguments[0]); // Kevin

console.log(arguments[1]); // Langley

}

logUser( 'Kevin', 'Langley' );

シナリオ3.プロトタイプメソッド
function User(firstName, lastName) {

this.name = `${firstName} ${lastName}`;

}

User.prototype.sayHello = () => {

return `Hello, ${this.name}`;

}

const me = new User( 'Kevin', 'Langley' );

me.sayHello(); // Hello,
The thissayHello メソッドはグローバルオブジェクトを参照しますUser アクセスしようとしているオブジェクト.
代わりに、プロトタイプ方法を古いやり方で書きなさい.
function User(firstName, lastName) {

this.name = `${firstName} ${lastName}`;

}

User.prototype.sayHello = function() {

return `Hello, ${this.name}`;

}

const me = new User( 'Kevin', 'Langley' );

me.sayHello(); // Hello, Kevin Langley

シナリオ4.オブジェクトメソッド
const user = {

 name: 'Kevin Langley',

sayHello: () => `Hello, ${this.name}`;

}

user.sayHello(); // Hello,
The thissayHello メソッドはグローバルオブジェクトを参照しますUser アクセスしようとしているオブジェクト.
代わりに、プロトタイプ方法を古いやり方で書きなさい.
const user = {

 name: 'Kevin Langley',

sayHello() {

return `Hello, ${this.name}`;

}

}

user.sayHello(); // Hello, Kevin Langley