Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีใช้คีย์เวิร์ด with ใน JavaScript


คีย์เวิร์ด with ใช้เป็นตัวย่อสำหรับอ้างอิงคุณสมบัติหรือเมธอดของออบเจกต์

ออบเจกต์ที่ระบุเป็นอาร์กิวเมนต์ของ with จะกลายเป็นออบเจกต์เริ่มต้นสำหรับระยะเวลาของบล็อกที่ตามมา คุณสมบัติและเมธอดของออบเจกต์สามารถใช้ได้โดยไม่ต้องระบุชื่อออบเจกต์

ไวยากรณ์

ไวยากรณ์ของ with object มีดังนี้:

with (object){    properties used without the object name and dot }

ตัวอย่าง

คุณสามารถลองรันโค้ดต่อไปนี้เพื่อเรียนรู้การใช้งาน with keyword:

Live Demo

<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