面向对象和面向过程
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div,
p {
height: 100px;
background-color: darksalmon;
margin: 10px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<script>
// 面向过程,代码有一部分是重复的
/* var divs = document.querySelectorAll("div");
for (var i = 0; i < divs.length; i++) {
divs[i].style.border = "2px solid yellow"
}
var ps = document.querySelectorAll("p");
for (var i = 0; i < ps.length; i++) {
ps[i].style.border = "2px solid blue"
} */
// 面向对象
/* function getSome(ele) {
return document.querySelectorAll(ele)
}
function getBorder(ele) {
for (var i = 0; i < ele.length; i++) {
ele[i].style.border = "2px solid purple"
}
}
getBorder(getSome("div"))
getBorder(getSome("p")) */
// ES5的写法
/* var tools = {
getEle: function(ele) {
return document.querySelectorAll(ele)
},
setBorder: function(ele) {
for (var i = 0; i < ele.length; i++) {
ele[i].style.border = "2px solid purple"
}
}
} */
// ES6的写法
var tools = {
getEle(ele) {
return document.querySelectorAll(ele)
},
setBorder(ele) {
for (var i = 0; i < ele.length; i++) {
ele[i].style.border = "2px solid purple"
}
}
}
tools.setBorder(tools.getEle("div"))
</script>
</body>
</html>