JavaScript WITH 语句有哪些用途?
WITH 语句用于指定给定属性的默认对象,并允许我们防止编写冗长的对象引用。它将给定对象添加到作用域链的头部。
以下是 JavaScript 中 with 语句的代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript with statement</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to get the first and lastname property of obj</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let obj = {
firstName: "Rohan",
lastName: "Sharma",
};
BtnEle.addEventListener("click", () => {
with (obj) {
resEle.innerHTML = "Welcome " + firstName + " " + lastName;
}
});
</script>
</body>
</html>输出
以上代码将产生以下输出 −

单击“点按此处”按钮 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP