如何在 JavaScript 中使用“with”關鍵字?
with 關鍵字用作引用物件的屬性或方法的一種速記。
指定為 with 引數的物件將成為後續程式碼塊期間的預設物件。可以使用該物件的屬性和方法,而無需指定物件名稱。
語法
for with object 的語法如下 −
with (object){
properties used without the object name and dot
}示例
嘗試學習以下程式碼,以瞭解如何實現 with 關鍵字 −
<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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP