Function.prototype.call() मेथड किसी फंक्शन को दिए गए 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: #fd7e14; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style> </head> <body>
<h1>JavaScript call() मेथड</h1>
<div class="sample"></div>
<button class="Btn">वयस्कता जांचें (call)</button>
<h3>ऊपर दिए गए बटन पर क्लिक करके जांचें कि वयस्क हैं या नहीं</h3>
<script>
const sampleEle = document.querySelector(".sample");
const person = { name: "रोहन", age: 22 };
function checkAdult(vehicle, country) {
if (this.age > 18) {
sampleEle.innerHTML = this.name + " आप वयस्क हैं और " + vehicle + " चला सकते हैं " + country + " में";
} else {
sampleEle.innerHTML = this.name + " आप वयस्क नहीं हैं और " + vehicle + " नहीं चला सकते " + country + " में";
}
}
document.querySelector(".Btn").addEventListener("click", () => {
checkAdult.call(person, 'कार', 'भारत');
});
</script> </body> </html>
आउटपुट
क्लिक करने पर: रोहन आप वयस्क हैं और कार चला सकते हैं भारत में
call() vs apply() vs bind()
| मेथड | आर्गुमेंट्स | निष्पादन | उपयोग |
|---|---|---|---|
call() | व्यक्तिगत (कॉमा सेपरेटेड) | तुरंत | त्वरित कॉल, ज्ञात आर्गुमेंट्स |
apply() | एरे/एरे-लाइक | तुरंत | डायनामिक आर्गुमेंट्स, Math.max आदि |
bind() | व्यक्तिगत | नया फंक्शन लौटाता है | बाद में उपयोग, इवेंट हैंडलर |
व्यावहारिक उदाहरण
// 1. एरे पर Math.max (apply के साथ बेहतर)
const numbers = [5, 10, 3, 8];
Math.max.call(null, ...numbers); // 10 (स्प्रेड ऑपरेटर)
Math.max.apply(null, numbers); // 10 (क्लासिक)
// 2. Array-like को Array में बदलें
function argsToArray() {
return Array.prototype.slice.call(arguments);
}
argsToArray(1, 2, 3); // [1, 2, 3]
// 3. मेथड उधार लेना
const obj = { name: "JS" };
Array.prototype.push.call(obj, "hello"); // {0: "hello", name: "JS", length: 1}
// 4. कंस्ट्रक्टर चेनिंग
function Parent(name) { this.name = name; }
function Child(name, age) { Parent.call(this, name); this.age = age; }