初識面向對象
1、面向對象和麪向過程的區別
面向過程
程序 = 算法 + 語法
弊端:1.問題規模增大,沒法控制後期代碼
2.代碼的複用性低
面向對象
程序 = 對象 + 對象 + 對象 + ...........
對象 : 被下定義的那個東西就是對象(您看到的,你想到的,有形的,無形的萬物皆爲對象)
2、類與對象的概念
類:大量的擁有相同屬性和行爲的對象的集合
對象:根據累的屬性和行爲而建立的實例化。對象是類的實例化(類是沒有空間的)
注:對象具備惟一性
舉例:
學生 紅孩兒、豬八戒 類與對象
水果 蘋果、香蕉、栗子 繼承、父子關係、無對象
面向對象的三大特色:封裝、繼承、多態
封裝:
繼承:
多態:
3、構造函數和對象的關係
a.普通構造函數
//對象的構造方法
function Student(newName,oldNem){
this.name = newName;
thid.tall = newTall;
this.eat =function(){
console.log("在吃飯");
}
this.code = function(){
console.log("在敲代碼");
}
}
b.ES6構造方法
class Birthday{
constructor(newY,newM,newD){
this.year = year;
this.month = month;
this.day = day;
}
showValue(){
console.log(this.year+","+this.month+","+this.date);
}
}
let bir = new Birthday(1989,3,12);
bir.showValue();
4、類與類之間的關係
關聯關係:對象和對象之間的鏈接。在面向對象中,其表現形式爲一個類的對象做爲另外一個類的屬性來存在。即has-a
依賴關係 :一個類的對象做爲另外一個類的成員對象存在。即use-a
指一個類A使用到了另外一個類。
<script>
class Car{
constructor(newSpeed) {
this.speed = newSpeed;
}
time(r){
return Number(r.length/this.speed);
}
}
class Road{
constructor(newLength) {
this.length = newLength;
}
}
let c = new Car(60);
let r = new Road(1000);
console.log(c.time(r));
</script>
----------------------------------------------------------------------
面向對象的解決問題的思路
1.找出該問題的有用對象
2.根據對象抽象出其數據和行爲,建立類
3.各個對象各司其職,執行程序