如何在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 教师闺蜜祝福语简短