Open zuppachu opened 5 years ago
class Dog {
constructor(name) {
this.name = name;
this.behavior = 0;
}
}
const halley = new Dog('Halley');
// Create new Dog instance
console.log(halley.name);
// Log the name value saved to halley
// Output: 'Halley'
解釋:
constructor()
然後跑碼
Week 5-2
物件導向設計(Object-Oriented Programming)
中國叫法為『面向對象』。
為什麼要有OOP?
function appendResult() { }
function inputNumber() { }
function inputOperator() { }
document.querySelector('.number').addEventListener('click', function(){ inputNumber(document.querySelector('.number').innerText) })
document.querySelector('.operator').addEventListener('click', function(){ inputOperator(document.querySelector('.number').innerText) })
物件導向最重要的兩概念:class (類別)與 instance(實體)
類別:像設計圖藍圖,定義有什麼東西、什麼 function 可以用? 舉例來說:蓋房子的建築藍圖,藍圖內規劃廚房、主臥室在哪?有幾間房間?
而根據藍圖所建造出來的房屋就是實體
PHP 中的 class
public 是預設。但很少用 public,因為別人可以亂改內容。
封裝 Encapsulation
把整個細節都藏在 class 裡面,外面無法看見細節,向外呈現的東西都非常簡潔。
$a->name = 'Leo'
實作,需改成$a->setName('Leo')
。$a = new Dog(); // a 是一個物件,同時也是 Dog 的 instance $a->name = ', my name is Leo'; $a->hello(); // 語法不同,在JS 裡面是 a.hello() // 得 I am a dog, my name is Leo
$b = new Dog(); $b->name = ', my name is Boo'; $b->hello(); //讓 b // 執行這個的時候 this 就是 b的名稱 // 得 I am a dog, my name is Boo
?>
原因:
getter
和setter
可以做檢查。// setter :專設定變數 public function setName($name){ if ($name === 'fuck') return; //如果是髒話,不執行 $this->name = $name; }
// getter:回傳變數 public function getName($name){ return $this->name; } ...
建構子:__construct
$a = new Dog('Leo'); //這樣可以先設定好初始化 $b = new Dog('Boo'); $a->hello(); $b->hello(); // 執行這個的時候 this 就是 b的名稱
?>
JavaScript 內的 Class
class Calculator { constructor(name) { this.name = name; } hello(){ console.log(this.name) } }
const calculator = new Calculator('my calculator') calculator.hello() //得 my calculaator
/ calculator.input(1) calculator.input('+') calculator.input(3) const result = calculator.getResult() console.log(result) /
其實 javascript 內沒有 class 關鍵字, javascript 還是希望能夠維持他原有的方式,所以可以利用常見的 fucntion 來操作替代 class 語法。
小結: 以上兩種寫法皆可。或許是 class 寫法比較好懂
繼承 Inheritance
狗也是一種動物,所以動物有的屬性,狗也會有。 可以改寫成 『繼承』,如下:
除了上述以外,還可以用 static 方法
靜態方法 Static vs 方法 Method
Class 本身也可以有 function 。這個好處是,這個東西本身不會被改變,然後是建立在 Dog 底下的 function
多型 Polymorphism
老師說之後會補充
參考
同學超詳細的筆記 :)
JavaScript 物件介紹:內有詳盡介紹 初學者應知道的物件導向 JavaScript
補充資料
給OOP初學者的建議:先搞懂「資料跟行為在一起」就好,其它的慢慢來 物件導向基礎:何謂類別(Class)?何謂物件(Object)? 物件導向基礎:何謂類別(Class)?何謂物件(Object)? [解答] 我要學會 Java (二):物件導向其實很簡單 什麼是物件導向程式設計呢?