示例代碼:javascript
// 類 class Person { constructor(name, age) { this.name = name // 屬性 姓名 this.age = age // 屬性 年齡 } // 方法 吃飯 eat() { alert(`${this.name} eat something.`) } // 方法 說話 speak() { alert(`My name is ${this.name}, my age is ${this.age}.`) } } // 對象 Person的具體實現 const xiaoming = new Person('xiaoming', 10) xiaoming.eat() xiaoming.speak()
class Person { constructor(name, age) { this.name = name this.age = age } eat() { alert(`${this.name} eat something.`) } speak() { alert(`My name is ${this.name}, my age is ${this.age}.`) } } // Student 繼承了 Person,具備 Person 的全部屬性,而且有本身的特有屬性 class Student extends Person { constructor(name, age, no) { super(name, age) this.no = no // 學生能夠有學號屬性 } // 學生能夠學習 study() { alert(`${this.name} study something.`) } } const xiaoming = new Student('xiaoming', 10, '10010') xiaoming.study()
public、protected、private
三個關鍵字,其中public
關鍵字修飾的屬性表示公有的屬性,能夠隨便訪問,protected
關鍵字修飾的屬性表示子類內部能夠訪問,private
關鍵字修飾的屬性只能在類內部訪問,外部沒法訪問(圖中+
表示共有屬性、#
表示子類能夠訪問、-
表示私有屬性,因爲 javascript 不支持這三種修飾符,因此此處用 typescript 演示,瞭解便可)。class Person { public name // 公有屬性,能夠隨便訪問 public age protected weight // 子類內部能夠訪問,外部沒法訪問 constructor(name, age) { this.name = name this.age = age this.weight = 120 } eat() { console.log(`${this.name} eat something.`) } speak() { console.log(`My name is ${this.name}, age is ${this.age}.`) } } class Student extends Person { private grilfriend // 私有屬性,只有在 Student 類內部才能夠訪問 constructor(name, age) { super(name, age) this.grilfriend = 'xiaoli' } study() { alert(`${this.name} study.`) } getWeight() { alert(`weight ${this.weight}.`) // protected 修飾的屬性子類內部能夠訪問 } } let xiaoming = new Student('xiaoming', 10) xiaoming.getWeight() alert(xiaoming.name) // alert(xiaoming.weight) // 報錯 // alert(xiaoming.grilfriend) // 報錯
class Person { constructor(name) { this.name = name } saySomething() {} } class A extends Person { constructor(name) { super(name) } saySomething() { alert('This is A.') } } class B extends Person { constructor(name) { super(name) } saySomething() { alert('This is B.') } }
定義一個建立對象的工廠,將建立者和構造函數分離,建立者不用關心具體構造函數的實現,符合開放封閉原則和最少知識原則。java
class Product { constructor(name) { this.name = name } init() { console.log('init.') } fn() { console.log('fn.') } } class Creator { create(name) { return new Product(name) } } const creator = new Creator() const obj = creator.create('obj') obj.init() obj.fn()
系統中被惟一使用,一個類只有一個示例,例如:typescript
class SingleObject { constructor() {} init() { console.log('init...') } } SingleObject.getInstance = (function() { let instance = null return function() { if (!instance) { instance = new SingleObject() } return instance } })() const obj1 = SingleObject.getInstance() obj1.init() const obj2 = SingleObject.getInstance() obj2.init() console.log(obj1 === obj2)