JavaSCRIPT: ファンク・コール・ファンク

WBOY
リリース: 2024-07-26 13:32:34
オリジナル
373 人が閲覧しました

JAVASCRIPT: FUNC CALLING FUNK

JavaScript の関数の概要

JavaScript は多用途で動的な言語として、関数を第一級市民として扱います。これは、関数を他のデータ型と同じように操作できることを意味します。これらは変数に割り当てたり、配列に格納したり、引数として他の関数に渡すことができます。この柔軟性は、ユーザー イベントに効果的に応答する JavaScript の機能の基礎となります。


質疑応答

Q1: 関数が JavaScript の第一級市民であるとはどういう意味ですか?
A1: JavaScript では、関数は第一級市民とみなされます。つまり、関数を変数に代入したり、引数として他の関数に渡したり、関数から返すことができます。これらは、他のデータ型と同様に操作できます。

Q2: 関数宣言を使用して JavaScript で関数を定義するにはどうすればよいですか?
A2: JavaScript の関数は、次のような関数宣言を使用して定義できます。

function functionName(parameters) {
    // function body
}
ログイン後にコピー

Q3: JavaScript のイベント リスナーとは何ですか?
A3: イベント リスナーは、HTML 要素で特定のイベントが発生したときに呼び出される関数です。これは、イベント タイプと呼び出される関数を引数として受け取る addEventListener メソッドを使用して要素に追加されます。

Q4: ID が「myButton」のボタンにクリック イベント リスナーを追加するにはどうすればよいですか?
A4: 次のように、クリック イベント リスナーを ID 'myButton' のボタンに追加できます:

document.getElementById('myButton').addEventListener('click', function() {
    alert('Button was clicked!');
});
ログイン後にコピー
ログイン後にコピー

Q5: イベント ハンドラーに匿名関数ではなく名前付き関数を使用するのはなぜですか?
A5: イベント ハンドラーに名前付き関数を使用すると、コードが読みやすく、再利用しやすくなります。名前付き関数は一度定義すれば何度でも使用できますが、匿名関数はデバッグや保守が難しいことがよくあります。

Q6: JavaScript でイベント リスナーを削除するにはどうすればよいですか?
A6: イベント リスナーは、removeEventListener メソッドを使用して削除できます。このメソッドには、イベント リスナーの追加時に使用された正確な関数参照が必要です。例:

document.getElementById('myButton').removeEventListener('click', handleClick);

ログイン後にコピー

関数とは何ですか?

JavaScript では、関数は特定のタスクを実行するように設計されたコードのブロックです。何かがそれを呼び出す(呼び出す)ときに実行されます。関数は、関数宣言または関数式を使用して定義できます。

`Function Declaration:
function greet(name) {
    return `Hello, ${name}!`;
}

Function Expression:
const greet = function(name) {
    return `Hello, ${name}!`;
};`
ログイン後にコピー

どちらのメソッドも、カプセル化したコードのブロックを実行するために呼び出すことができる関数を作成します。

第一級国民

プログラミング言語における「第一級市民」という用語は、引数として関数に渡したり、関数から返したり、変数に代入したりできるエンティティを指します。 JavaScript では、関数がこのステータスを享受し、高階関数とコールバックを有効にします。

関数を変数に代入する例:

`const sayHello = function(name) {
    return `Hello, ${name}!`;
};
console.log(sayHello('Alice'));`
ログイン後にコピー

関数を引数として渡す例:

function callWithArgument(fn, arg) {
    return fn(arg);
}
console.log(callWithArgument(sayHello, 'Bob'));
ログイン後にコピー

ユーザーイベントへの応答

ユーザー イベントは、ボタンのクリック、テキスト フィールドへの入力、マウスの移動など、ユーザーによって実行されるアクションです。 JavaScript はイベント リスナーを使用してこれらのイベントに応答します。イベント リスナーは、HTML 要素でイベントが検出されたときに呼び出される関数です。

イベントリスナーの追加

Web ページをインタラクティブにするには、addEventListener メソッドを使用して HTML 要素にイベント リスナーを追加します。このメソッドは 2 つの引数を取ります。イベント タイプと、イベントの発生時に呼び出す関数です。

例:

document.getElementById('myButton').addEventListener('click', function() {
    alert('Button was clicked!');
});
ログイン後にコピー
ログイン後にコピー

この例では、addEventListener メソッドを使用して、ID が myButton のボタンにクリック イベントをアタッチします。ボタンをクリックすると、アラートボックスが表示されます。

イベント ハンドラーに名前付き関数を使用する
匿名関数 (上に示したもの) はイベント処理によく使用されますが、名前付き関数を使用すると、コードが読みやすく再利用しやすくなります。

例:

function handleClick() {
    alert('Button was clicked!');
}

document.getElementById('myButton').addEventListener('click', handleClick);
ログイン後にコピー

この例では、handleClick 関数が個別に定義され、addEventListener に渡されます。

イベントリスナーの削除

イベント リスナーは、removeEventListener メソッドを使用して削除できます。このメソッドには、イベント リスナーの追加時に使用された正確な関数参照が必要です。

例:

document.getElementById('myButton').removeEventListener('click', handleClick);
ログイン後にコピー

イベント リスナーの削除は、リソースを管理し、複雑なアプリケーションでのメモリ リークを回避するのに役立ちます。

その他の例:

DOM (ドキュメント オブジェクト モデル) の操作には、多くの場合、匿名関数を含む関数を引数として他の関数に渡すことが含まれます。これは、イベント処理、動的なコンテンツ更新、および複雑な変換の適用に特に役立ちます。この概念を説明するための実際的な例をいくつか示します。

Example 1: Event Handling with Anonymous Functions
In event handling, it's common to pass an anonymous function directly into addEventListener.

document.getElementById('submitBtn').addEventListener('click', function(event) {
    event.preventDefault(); // Prevent the default form submission behavior
    const inputText = document.getElementById('textInput').value;
    console.log(`Submitted text: ${inputText}`);
});
ログイン後にコピー

In this example, the anonymous function passed to addEventListener handles the click event on the button with the ID submitBtn. It prevents the default form submission and logs the input text.

Example 2: Array Methods with Anonymous Functions
Array methods like forEach, map, and filter often use anonymous functions to manipulate the DOM based on the array's content.

const listItems = document.querySelectorAll('li');
listItems.forEach(function(item, index) {
    item.textContent = `Item ${index + 1}`;
}); 
ログイン後にコピー

Here, an anonymous function is passed to forEach to update the text content of each list item with its respective index.

Example 3: Creating Dynamic Content
You can use anonymous functions to create and manipulate DOM elements dynamically.

document.getElementById('addItemBtn').addEventListener('click', function() {
    const newItem = document.createElement('li');
    newItem.textContent = `New Item ${Date.now()}`;
    document.getElementById('itemList').appendChild(newItem);
}); 
ログイン後にコピー

In this example, clicking the button with the ID addItemBtn triggers an anonymous function that creates a new list item and appends it to the list with the ID itemList.

Example 4: Custom Event Handling
Sometimes, you may want to pass functions into custom event handlers.

function handleCustomEvent(eventHandler) {
    document.getElementById('triggerBtn').addEventListener('click', function() {
        const eventDetail = { message: 'Custom event triggered' };
        eventHandler(eventDetail);
    });
}

handleCustomEvent(function(eventDetail) {
    console.log(eventDetail.message);
});
ログイン後にコピー

In this scenario, handleCustomEvent accepts an anonymous function as an argument and uses it as an event handler for a custom event triggered by clicking the button with the ID triggerBtn.

Example 5: SetTimeout and SetInterval
The setTimeout and setInterval functions often use anonymous functions to perform actions after a delay or at regular intervals.

setTimeout(function() {
    document.getElementById('message').textContent = 'Timeout triggered!';
}, 2000);

let counter = 0;
const intervalId = setInterval(function() {
    counter++;
    document.getElementById('counter').textContent = `Counter: ${counter}`;
    if (counter === 10) {
        clearInterval(intervalId);
    }
}, 1000);
ログイン後にコピー

Here, the first anonymous function updates the text content of an element with the ID message after a 2-second delay. The second anonymous function increments a counter and updates the text content of an element with the ID counter every second until the counter reaches 10, at which point the interval is cleared.

Passing functions, including anonymous functions, into other functions is a powerful technique in JavaScript for DOM manipulation and event handling. These examples demonstrate how you can leverage this feature to create dynamic and interactive web applications. Whether you're handling events, updating content dynamically, or using built-in methods like setTimeout, understanding how to pass functions effectively will enhance your ability to work with the DOM.

以上がJavaSCRIPT: ファンク・コール・ファンクの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!