面向對象 why? 1.程式執行:順序,判斷,迴圈, 結構化 2.面向對象 數據結構化 3.面向電腦,結構化的才是最簡單的 4.變成應該 簡單&抽象 一個基本的類 javascript class People { constructor(name, age) { this.name = name ...
面向對象
why?
1.程式執行:順序,判斷,迴圈,----結構化
2.面向對象----數據結構化
3.面向電腦,結構化的才是最簡單的
4.變成應該 簡單&抽象
一個基本的類
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
alert(`${this.name} eat something`);
}
speak() {
alert(`My name is ${this.name}, age ${this.age}`);
}
}
let zhang = new People("zhang", 20);
zhang.eat();
zhang.speak();
let wang = new People("wang", 21);
wang.eat();
wang.speak();
繼承
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
alert(`${this.name} eat something`);
}
speak() {
alert(`My name is ${this.name}, age ${this.age}`);
}
}
class Student extends People {
constructor(name, age, number) {
super(name, age);
this.number = number;
}
study() {
alert(`${this.name} study`);
}
}
let xiaoming = new Student("xiaoming", 10, "A1");
xiaoming.study();
console.log(xiaoming.number);
let xiaohong = new Student("xiaohong", 11, "A2");
xiaohong.study();
多態
同一個介面,不同表現
js 應用極少
需要結合 java 等語言的介面,重寫,重載等功能
保持子類的開放性和靈活性
面向介面編程
(js 引用極少)
class People {
constructor(name) {
this.name = name;
}
saySomething() {}
}
class A extends People {
constructor(name) {
super(name);
}
saySomething() {
alert("I am A");
}
}
class B extends People {
constructor(name) {
super(name);
}
saySomething() {
alert("I am B");
}
}
let a = new A("a");
a.saySomething();
let b = new B("b");
b.saySomething();
封裝
減少耦合,不該外露的不外露
利於數據,介面的管理
es6 不支持,一般認為,_開頭的屬性是 private
封裝在 es6 中無法體現,因為是通過 public,protect,和 private 體現的,但在 ts 中可以體現
class People {
// ts中嚴格:變數要使用先定義,預設為public
name;
age;
protected weight; //受保護的屬性只有自己可訪問
constructor(name, age) {
this.name = name;
this.age = age;
this.weight = 120;
}
eat() {
alert(`${this.name} eat something`);
}
speak() {
alert(`My name is ${this.name}, age ${this.age}`);
}
}
class Student extends People {
number;
private girlfriend;
constructor(name, age, number) {
super(name, age);
this.number = number;
this.girlfriend = "ygj";
}
study() {
alert(`${this.name} study`);
}
getweight() {
alert(`${this.weight}`);
}
}
let xiaoming = new Student("zhang", 20, "11");
xiaoming.getweight(); //不報錯
alert(xiaoming.girlfriend); //報錯
alert(xiaoming.weight); //報錯
let wang = new People("wang", 21);
wang.eat();
wang.speak();
jQuery 使用類的示例
class jQuery {
constructor(selector) {
let slice = Array.prototype.slice;
let dom = slice.call(document.querySelectorAll(selector));
let len = dom ? dom.length : 0;
for (let i = 0; i < len; i++) {
this[i] = dom[i];
}
this.length = len;
this.selector = selector || "";
}
append(node) {}
addClass(name) {}
html(data) {}
// 此處省略若幹 API
}
window.$ = function(selector) {
return new jQuery(selector);
};
// 測試代碼
var $p = $("p");
console.log($p);
console.log($.addClass);
UML類圖
統一建模語言
類圖,UML包含很多種圖
關係,泛型,和關聯
泛型是指繼承(空心)
關聯是指引用(實心)