如何在 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