JavaScript面向对象编程和面向过程编程
JavaScript编程中多数情况是面向过程编程,但有时候为了更好地封装重用。面向对象思想来编程更为有用。
虽然现前端都开始流行MVC思想的js框架,但并不是说js没用了,学好js对于学习js前端框架,jquery,等都是非常有帮助的。
好了,闲话不说,下面用一个例子,两种写法,来说明面向对象和面向过程编程。
效果如上,一个简简单单的选项卡的例子。
面向过程编程代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1.active{
background-color: red;
}
#div1 div{
background: gray;
width: 200px;
height: 200px;
display: none;
border: solid black 1px;
}
#div1{background: yellow;}
</style>
<script type="text/javascript">
var oBtns;
var oDivs;
window.onload=function(){
var oDiv1 = document.getElementById('div1');
oBtns = oDiv1.getElementsByTagName('input');
oDivs = oDiv1.getElementsByTagName('div');
for(var i = 0;i<oBtns.length;i++){
oBtns[i].index = i;
oBtns[i].onclick = function(){
for(var j = 0;j<oBtns.length;j++){
oBtns[j].className='';
oDivs[j].style.display='none';
}
this.className='active';
oDivs[this.index].style.display='block';
};
}
}
</script>
</head>
<body>
<div id="div1">
<input type="button" value="xxx" />
<input type="button" value="qqq" />
<input type="button" value="aaa" />
<div style="display: block;">
111
</div>
<div >
222
</div>
<div >
333
</div>
</div>
</body>
</html>
总结:面向过程编码,代码较为简洁,过程清楚明了,较容易理解。
面向对象编程代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1 input.active{
background-color: red;
}
#div1 div{
background: gray;
width: 200px;
height: 200px;
display: none;
border: solid black 1px;
}
#div1 input{background: yellow;}
</style>
<script type="text/javascript">
window.onload = function(){
new TabSwitch('div1');
}
function TabSwitch(id){
var _this = this;
var oDiv = document.getElementById(id);
this.aBtn = oDiv.getElementsByTagName('input');
this.aDiv = oDiv.getElementsByTagName('div');
for(var i = 0;i<this.aBtn.length;i++){
this.aBtn[i].index = i;
this.aBtn[i].onclick = function(){
_this.fnClick(this);
};
}
}
TabSwitch.prototype.fnClick = function(obtn){
for(var j = 0;j<this.aBtn.length;j++){
this.aBtn[j].className='';
this.aDiv[j].style.display='none';
}
obtn.className='active';
this.aDiv[obtn.index].style.display='block';
}
</script>
</head>
<body>
<div id="div1">
<input type="button" value="xxx" />
<input type="button" value="qqq" />
<input type="button" value="aaa" />
<div style="display: block;">
111
</div>
<div >
222
</div>
<div >
333
</div>
</div>
</body>
</html>
总结:面向对象编程较不容易理解,其中this用法容易用错。但是面向对象编程重用性更好,封装更彻底。以后想使用选项卡这个功能,直接引入js文件妥妥的。