體會面向物件過程與面向物件的程式設計思想
阿新 • • 發佈:2019-01-04
體會面向物件過程與面向物件的程式設計思想
加粗樣式
<script> // 初級面向物件思想 document.getElementById('btn').onclick=function(){ document.getElementById("dv").style.backgroundColor="yellow"; }; // 高階面向物件思想 // 按鈕是一個物件,div是一個物件,顏色是屬性 //建構函式 function ChangeColor(btnId,dvId,color){ this.btnObj=document.getElementById(btnId);//按鈕物件 this.dvObj=document.getElementById(dvId);//div物件 this.color=color; } //資料共享方式來改變背景顏色 ChangeColor.prototype.init=function(){ console.log(this);//this就是當前物件那個-----就是例項物件--就是S1 var that = this; this.btnObj.onclick=function(){ that.dvObj.style.backgroundColor=that.color; } }; //例項化物件 var s1 = new ChangeColor("btn","dv","yellow"); s1.init(); </script>