面向对象
概念
类-模板
对象-实例
// 类-模板
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
console.log(`${this.name} 吃 饭饭 `);
}
speak() {
console.log(`我叫 ${this.name},今年 ${this.age} 岁`);
}
}
// 对象-实例
const p1 = new People("黄金胡", 18);
p1.eat();
p1.speak();
三要素
- 继承,子类继承父类
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
console.log(`${this.name} 吃 饭饭 `);
}
speak() {
console.log(`我叫 ${this.name},今年 ${this.age} 岁`);
}
}
class Student extends People {
weight(weight) {
throw new Error("Method not implemented.");
}
getWeight() {
throw new Error("Method not implemented.");
}
constructor(name, age, number) {
super(name, age);
this.number = number;
this.girlfriend = undefined;
}
study() {
alert(`${this.name} 学习`);
}
}
const s1 = new Student("黄大仙", 66, "00252054");
s1.eat();
s1.speak();
s1.study();
封装,数据的权限和保密
- public 完全开放
- protected 对子类开放
- private 对自己开放
js 中没有上述 3 个关键字,ts 有
- 减少耦合,不该外露的不外露
- 利于数据、接口的权限管理
- ES6 目前不支持,一般认为_开头的属性是 private
class People {
name: String;
age: Number;
protected weight: Number; //受保护的属性,只有自己或者子类可以访问
constructor(name: String, age: Number) {
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: String;
private girlfriend;
constructor(name: String, age: Number, number: String) {
super(name, age);
this.number = number;
this.girlfriend = "xiaoli";
}
study() {
alert(`${this.name} study`);
}
getWeight() {
alert(`weight ${this.weight}`);
}
}
let xiaoming = new Student("xiaoming", 10, "A1");
xiaoming.getWeight();
alert(xiaoming.girlfriend);
alert(xiaoming.weight);
- 多态,同一接口不同实现
- 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();
为什么使用面向对象?
程序执行:顺序、判断、循环---结构化
面向对象---数据结构化
对于计算机,结构化才是最简单的
编程应该 简单&抽象