示例代码: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)