面向对象与面向过程的区别总结:
面向对象和面向过程都是一种编程思想,只是方式不一样;
面向过程:凡事亲力亲为,一步步按照过程写,注重的是整个过程和流程;
面向对象:执行者成为总指挥,分工协作,只要找到对象,然后让对象负责相关的事情,最后完成就可以了,注重的是结果;
面向对象的特性:封装,继承,多态
封装:就是指代码的封装,把一些通用的特征或者行为封装在对象中;
面向对象的编程思想:根据需求,抽象化出相关的对象,总结对象的行为特征,把特征变成属性,行为变成方法,然后自定义构造函数,然后通过构造函数实例化对象,通过对象调用相关的属性和方法,完成相应的需求;
js简单写法:
需求:点击input按钮,改变一个div的样式;
1.面向过程写法:
<input type="button" value="点击0" onclick="changeColor()"/>
<p id="p0">窗前明月光,疑是地上霜</p>
<script>
function changeColor(){
let ele = document.getElementById('p0');
ele.style.backgroundColor="blue";
}
</script>
2.面向对象写法:
<input type="button" id="h1" value="点击1"/>
<p id="p1">窗前明月光,疑是地上霜</p>
<input type="button" id="h2" value="点击1"/>
<p id="p2">举头望明月,低头思故乡</p>
<script>
window.onload=function(){
function Style(btnId,divId,json){
this.inputObj=document.getElementById(btnId);
this.divObj=document.getElementById(divId);
this.json=json;
}
Style.prototype.changeCss=function(){
let that=this;
this.inputObj.onclick=function(){
for(let key in that.json){
that.divObj.style[key]=that.json[key];
}
}
}
let json1 ={backgroundColor:"red",width:"200px",height:"100px"}
let obj1=new Style("h1","p1",json1);
obj1.changeCss();
let json2 ={backgroundColor:"yellow",width:"200px",height:"100px"}
let obj2 =new Style("h2","p2",json2);
obj2.changeCss();
}
</script>
3.es6 的面向对象写法
<input type="button" id="h1" value="点击1"/>
<p id="p1">窗前明月光,疑是地上霜</p>
<input type="button" id="h2" value="点击1"/>
<p id="p2">举头望明月,低头思故乡</p>
<script>
window.onload=function(){
class Style{
constructor(btnId,divId,json){
this.inputObj=document.getElementById(btnId);
this.divObj=document.getElementById(divId);
this.json=json;
}
changeCss(){
let that =this;
this.inputObj.onclick=function(){
for(let key in that.json){
that.divObj.style[key]=that.json[key];
}
}
}
}
let json1 ={backgroundColor:"red",width:"200px",height:"100px"}
let obj1=new Style("h1","p1",json1);
obj1.changeCss();
let json2 ={backgroundColor:"yellow",width:"200px",height:"100px"}
let obj2 =new Style("h2","p2",json2);
obj2.changeCss();
}
</script>