ต่อไปนี้เป็นรหัสสำหรับส่ง JavaScript ดั้งเดิมและประเภทวัตถุไปยังฟังก์ชัน -
ตัวอย่าง
<!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; } .result { font-size: 18px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Passing primitive/object types to function</h1> <div class="result"></div> <div class="result"></div> <button class="Btn">Click here</button> <h3>Click on the above button to pass primitive and object to a function and call it</h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); let person = { name: "Rohan", age: 12, city: "Delhi" }; function printObj(obj) { resEle.innerHTML = "Name = " + obj.name + "<br>"; resEle.innerHTML += "age = " + obj.age + "<br>"; resEle.innerHTML += "city = " + obj.city + "<br>"; } function printPrimitive(prim) { resEle.innerHTML += prim; } BtnEle.addEventListener("click", () => { printObj(person); printPrimitive(22); }); </script> </body> </html>
ผลลัพธ์
เมื่อคลิกปุ่ม 'คลิกที่นี่' -