如何在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 婆婆高寿祝福语大全简短