Function.prototype.apply() मेथड call() के समान है लेकिन आर्गुमेंट्स को एक एरे (या एरे-लाइक ऑब्जेक्ट) के रूप में स्वीकार करता है। यह डायनामिक आर्गुमेंट लिस्ट के लिए उपयोगी है।
उदाहरण
<!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: #20c997; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style> </head> </head> <body>
<h1>JavaScript apply() मेथड</h1>
<div class="sample"></div>
<button class="Btn">वयस्कता जांचें (apply)</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.apply(person, ["कार", "भारत"]);
});
</script> </body> </html>
आउटपुट
क्लिक करने पर: रोहन आप वयस्क हैं और कार चला सकते हैं भारत में
apply() के विशिष्ट उपयोग मामले
1. एरे पर Math फंक्शंस
const nums = [5, 10, 3, 8, 1]; Math.max.apply(null, nums); // 10 Math.min.apply(null, nums); // 1 // ES6 स्प्रेड ऑपरेटर (आधुनिक विकल्प) Math.max(...nums); // 10
2. कंस्ट्रक्टर चेनिंग
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price, expiry) {
Product.apply(this, [name, price]); // या Product.call(this, name, price)
this.expiry = expiry;
}
const apple = new Food("सेब", 50, "2024-12-31");
3. Array-like ऑब्जेक्ट्स मर्ज करना
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; Array.prototype.push.apply(arr1, arr2); // arr1 अब [1,2,3,4,5,6] // ES6 विकल्प arr1.push(...arr2);
4. arguments ऑब्जेक्ट हैंडलिंग
function sum() {
return Array.prototype.reduce.apply(arguments, [(a, b) => a + b]);
}
sum(1, 2, 3, 4); // 10