如何在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
热门推荐
1 潜能开发训练狗狗
2 狗狗多会训练好
3 扣篮训练狗狗
5 狗狗不训练
6 少儿柔术训练狗狗
8 训练好狗狗
9 训练狗狗怎么训
10 狗狗训练猫咪
11 狗狗训练地点
12 两个多月的狗狗怎么训练
13 怎么训练狗狗去厕所拉屎
14 狗狗怎样训练大小便
15 训练狗狗母
16 怎么训练狗狗坐下和握手
17 近视训练狗狗
18 狗狗倒的训练