JavaScript में फंक्शन को चार तरीकों से इनवोक (कॉल) किया जा सकता है, प्रत्येक अलग this बाइंडिंग व्यवहार के साथ।
उदाहरण
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.sample { font-size: 18px; font-weight: 500; }
button { padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style> </head> <body>
<h1>JavaScript फंक्शन इनवोकेशन</h1>
<div class="sample"></div>
<button class="Btn">फंक्शन इनवोक करें</button>
<h3>ऊपर दिए गए बटन पर क्लिक करके फंक्शन इनवोक करें</h3>
<script>
const sampleEle = document.querySelector(".sample");
function helloWorld() {
alert("HELLO WORLD");
}
document.querySelector(".Btn").addEventListener("click", () => {
helloWorld(); // साधारण इनवोकेशन
});
</script> </body> </html>
आउटपुट
अलर्ट बॉक्स में "HELLO WORLD" प्रदर्शित होगा।
फंक्शन इनवोकेशन के 4 तरीके
| तरीका | सिंटैक्स | this बाइंडिंग | उदाहरण |
|---|---|---|---|
| 1. फंक्शन के रूप में | func() | सख्त मोड: undefined, अन्यथा: window/global | myFunc() |
| 2. मेथड के रूप में | obj.method() | obj (कॉलिंग ऑब्जेक्ट) | obj.greet() |
| 3. कंस्ट्रक्टर के रूप में | new Func() | नया खाली ऑब्जेक्ट | new Person() |
| 4. अप्रत्यक्ष (call/apply/bind) | func.call(thisArg, ...) | निर्दिष्ट thisArg | func.call(obj) |
व्यावहारिक उदाहरण
const obj = {
value: 42,
getValue() { return this.value; }
};
// 1. फंक्शन के रूप में
const fn = obj.getValue;
fn(); // undefined (सख्त मोड) या window.value
// 2. मेथड के रूप में
obj.getValue(); // 42
// 3. कंस्ट्रक्टर
function Person(name) { this.name = name; }
const p = new Person("रोहन"); // this = nया ऑब्जेक्ट
// 4. अप्रत्यक्ष
fn.call({value: 100}); // 100
fn.apply({value: 200}); // 200
const bound = fn.bind({value: 300});
bound(); // 300
IIFE (तुरंत इनवोक्ड फंक्शन एक्सप्रेशन)
// क्लासिक
(function() { console.log("IIFE"); })();
// ES6 मॉड्यूल में कम जरूरी, लेकिन अभी भी उपयोगी
(() => { console.log("एरो IIFE"); })();