ใน JavaScript .call และ .apply ถูกพิจารณาว่าเป็นเมธอดของฟังก์ชันอ็อบเจกต์
.call method
นับจำนวนอาร์กิวเมนต์ด้วย call method รับอาร์กิวเมนต์หนึ่งหรือมากกว่าว่าเป็นอ็อบเจกต์
ไวยากรณ์:
.call(object, "argument1", "argument2");
.apply method
เพื่อใช้ array เป็นอาร์กิวเมนต์ ให้ใช้ .apply ต้องการ array เป็นอาร์กิวเมนต์ตัวที่ 2
ไวยากรณ์:
.apply(object, ["argument1", "argument[]"]);
ตัวอย่าง
ลองดูตัวอย่างแสดงทั้ง call และ apply method:
<!DOCTYPE html> <html>
<head>
<body>
<script>
var p = {
q: "Hello"
}
function showResult(v) {
document.write(this.q + " " + v);
}
showResult.call(p, "Amit"); // one or more objects as argument
showResult.apply(p, ["World"]); // array as the second argument
</script>
</body>
</head> </html>