JavaScriptで矢印関数を使用しない場合
10389 ワード
矢印機能は、従来の関数式により簡潔な代替手段ですが、どこにも適切ではありません.
あなたが矢関数を使いたくない何回かの例をチェックしましょう.
シナリオ1動的なコンテキストを必要とするコールバック関数.
要素のクリックなどの動的コンテキストを必要とするコールバック関数は、定義済みのコンテキストを変更できないため、矢印関数の候補となりません
シナリオ2を使う関数
矢印関数はグローバルにバインドされません
シナリオ3.プロトタイプメソッド
代わりに、プロトタイプ方法を古いやり方で書きなさい.
シナリオ4.オブジェクトメソッド
代わりに、プロトタイプ方法を古いやり方で書きなさい.
あなたが矢関数を使いたくない何回かの例をチェックしましょう.
シナリオ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 this
値sayHello
メソッドはグローバルオブジェクトを参照します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 this
値sayHello
メソッドはグローバルオブジェクトを参照しますUser
アクセスしようとしているオブジェクト.代わりに、プロトタイプ方法を古いやり方で書きなさい.
const user = {
name: 'Kevin Langley',
sayHello() {
return `Hello, ${this.name}`;
}
}
user.sayHello(); // Hello, Kevin Langley
Reference
この問題について(JavaScriptで矢印関数を使用しない場合), 我々は、より多くの情報をここで見つけました https://dev.to/kevinlangleyjr/when-to-not-use-arrow-functions-in-javascript-f91テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol