面向對象與面向過程的區別總結:
面向對象和麪向過程都是一種編程思想,只是方式不一樣;
面向過程:凡事親力親爲,一步步按照過程寫,注重的是整個過程和流程;
面向對象:執行者成爲總指揮,分工協作,只要找到對象,然後讓對象負責相關的事情,最後完成就可以了,注重的是結果;
面向對象的特性:封裝,繼承,多態
封裝:就是指代碼的封裝,把一些通用的特徵或者行爲封裝在對象中;
面向對象的編程思想:根據需求,抽象化出相關的對象,總結對象的行爲特徵,把特徵變成屬性,行爲變成方法,然後自定義構造函數,然後通過構造函數實例化對象,通過對象調用相關的屬性和方法,完成相應的需求;
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>