注意:该文章为自己初步学习用,不适合他人学习,请移步高赞文章。
面向对象是一种对现实世界阐述清晰的方式。
在项目中,特别是typescript中我们主要以OOP编程为项目结构的方式为主。
这里我们简要概述对象三板斧和UML制图
一板斧:继承
class Person {
constructor(name){
this.name = name
}
sayHi() {
console.log('Hi~ ' + this.name)
}
}
class Student {
constructor(name, grilFriend){
super(name)
this.grilFriend = grilFriend
}
}
Student是继承自Person的,拥有Person下的参数与方法。
二板斧:封装
封装的含义就是 清晰属性与方法是否进行暴露 。
public 完全公开访问
protected 只对自身与子类内部开放
private 只对自身内部开放
class Person {
public name
protected age
constructor(name,age){
this.name = name
this.age = age
}
sayHi() {
console.log('Hi~ ' + this.name)
}
}
class Student {
private grilFriend
constructor(name,age, grilFriend){
super(name,age)
this.grilFriend = grilFriend
}
}
这个时候子类Student可以访问到父类的方法和变量,但是经过student构建的对象,只能访问name,其他的都被隐藏起来了。
三板斧:多态
多态就是子类可以改变父类的方法,构建更适合自己的方式。
class Person {
constructor(name){
this.name = name
}
sayHi() {
console.log('Hi~ ' + this.name)
}
}
class Student {
constructor(name, grilFriend){
super(name)
this.grilFriend = grilFriend
}
sayHi() {
console.log('Hi~ ' + this.name +' student.')
}
}
这个时候,子类就将父类的sayHi方法进行覆盖,这样称作多态。
三板斧示例
class myJquery {
constructor(selector) {
this.selector = document.querySelectorAll(selector)[1] ?
document.querySelectorAll(selector) :
document.querySelector(selector);
}
// 下面写一些方法
showHTML() {
return this.selector.innerHTML
}
}
// 工厂模式
window.$ = (selector) => {
return new myJquery(selector)
}
console.log($('#app').showHTML())
UML制图
制图网站: processone.com
为什么我们要制图?因为一个项目往往有很多对象与方法,如果没有清晰的图表标识,经过我们自己去梳理,还是比较不方便的。
遵循原则
类名
----
变量列表
----
方法列表
----
1.状态 变量名(方法):类型
2.“+” 公有成员与方法
“#” 内部成员与方法
“-” 私有成员与方法