如何在JavaScript中使用'with'关键字?
with关键字用作引用对象的属性或方法的一种简写形式。
指定为with的参数的对象在随后的块持续时间内成为默认对象。可以使用该对象的属性和方法而无需命名该对象。
语法
with对象的语法如下-
with (object){
properties used without the object name and dot
}示例
您可以尝试学习以下代码,以了解如何使用关键字实现-
<html>
<head>
<title>User-defined objects</title>
<script>
//定义一个将用作方法的函数
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", "Nhooo");
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 : Nhooo Book price is : 100
热门推荐
10 生日祝福语朋友简短的话
11 宝贝的人生祝福语简短
12 新年有哪些祝福语简短
13 简短又洋气祝福语大全
14 简短祝福语除夕快乐英文
15 生日贺卡祝福语毕业简短
16 战友聚会祝福语幽默简短
17 最新中秋祝福语简短英语
18 夏日升学宴祝福语简短