ใช้คีย์เวิร์ด with เป็นตัวย่อสำหรับอ้างอิงคุณสมบัติหรือเมธอดของออบเจ็กต์
อ็อบเจ็กต์ที่ระบุเป็นอาร์กิวเมนต์ with จะกลายเป็นออบเจ็กต์เริ่มต้นสำหรับช่วงเวลาของบล็อกที่ตามมา คุณสมบัติและเมธอดสำหรับอ็อบเจ็กต์สามารถใช้ได้โดยไม่ต้องตั้งชื่ออ็อบเจกต์
ไวยากรณ์
ไวยากรณ์สำหรับ with object มีดังนี้ -
with (object){
properties used without the object name and dot
} ตัวอย่าง
คุณสามารถลองเรียนรู้โค้ดต่อไปนี้เพื่อเรียนรู้วิธีใช้งานด้วยคีย์เวิร์ด −
การสาธิตสด
<html>
<head>
<title>User-defined objects</title>
<script>
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Python", "Tutorialspoint");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html> ผลลัพธ์
Book title is : Python Book author is : Tutorialspoint Book price is : 100