然而木有对象
JS类的认识
abstract 定义抽象类
// abstract 关键字加在 class 前面定义抽象类
abstract class TestAbstract {
aName:string // 不指定访问修饰符时默认为 public,任何地方均可访问
static a: number = 1 // 使用 static 关键字定义静态变量
readonly x: number // 使用 readonly 关键字将属性设置为只读的,只读属性必须在声明时或构造函数里被初始化
private _y: number // private 关键字定义私有属性,仅当前类可以访问
protected p1: string = '默认值' // protected 关键字修饰的属性只能在当前类或子类中访问
p2: number = 1 // 定义属性时指定默认值就不用必须在构造方法中初始化
p3?: number // 使用 ?定义为可选属性就不用必须在构造方法中初始化
constructor(aName:string, x: number, y: number) {
this.x = x // 定义属性时如果没有默认值,就一定要在构造方法中初始化,否则会编译失败
this.aName = aName
this._y = y
}
// 定义静态方法
static distanceBetween(a: TestAbstract, b: TestAbstract): number {
var dx = a.x - b.x
var dy = a.y - b.y
return Math.sqrt(dx * dx + dy * dy)
}
}
觉得抽象类和类也并没有啥特殊的,不知为啥要搞个abstract 关键字来定义抽象类,用类也是一样的
类的扩充
1、interface接口
定义接口
// 通过 interface 关键字定义接口、契约
interface Shape {
color: string // 除了定义方法契约,还可以定义属性契约,要求实现该接口的类必须重写该属性
setColor(color: string): void // 定义方法契约
}
// 接口可以多继承
interface SXXXquare extends Shape, XXX {
setSideLength(sideLength: number): void
}
interface Other {
testOther(): void
}
实现接口
// 通过 implements 关键字实现接口、契约
class SquareDemo implements SXXXquare, Other {
color: string
constructor(color: string) {
this.color = color
}
setSideLength(sideLength: number): void {}
setColor(color: string): void {}
testOther(): void {}
}
方法
箭头函数、this
默认情况下,普通函数中的 this 指向的是顶层对象
箭头函数中的 this 指向的是当前对象
class TestThisOne {
userName: string = 'TestThisOne'
normalFunction(p1: string): string {
// 默认情况下,普通函数中的 this 指向的是顶层对象
if (this instanceof TestThisOne) {
console.log(` TestThisOne的子类 normalFunction方法调用 非箭头函数输出 ${this} 。`)
} else {
console.log(` 非TestThisOne的子类 normalFunction方法调用 非箭头函数输出 ${this} 。`)
}
console.log(`normalFunction P1 is ${p1} 。`)
return p1
}
arrowFunction = (p1: string): string => {
// 箭头函数中的 this 指向的是当前对象
if (this instanceof TestThisOne) {
console.log(`TestThisOne的子类调用 arrowFunction箭头函数 输出 ${this} 。`)
} else {
console.log(`非TestThisOne的子类调用 arrowFunction箭头函数 输出 ${this} 。`) //箭头函数走不到这里来!!
}
console.log(`arrowFunction P1 is ${p1} 。`)
return p1
}
}
class TestThisTwo {
userName: string = 'TestThisTwo'
test() {
let testThisOne = new TestThisOne()
testThisOne.normalFunction('ignore') // TestThisOne的子类 normalFunction方法调用 非箭头函数输出 [object Object] 。
testThisOne.arrowFunction('ignore') // TestThisOne的子类调用 arrowFunction箭头函数 输出 [object Object] 。
let normalFunction = testThisOne.normalFunction
normalFunction('ignore') // 非TestThisOne的子类 normalFunction方法调用 非箭头函数输出 [object DedicatedWorkerGlobalScope] 。
normalFunction = normalFunction.bind(testThisOne)
normalFunction('ignore') // TestThisOne的子类 normalFunction方法调用 非箭头函数输出 [object Object] 。
let arrowFunction = testThisOne.arrowFunction
arrowFunction('ignore') // TestThisOne的子类调用 arrowFunction箭头函数 输出 [object Object] 。
}
}
//调用======================
class Other {
render() {
let testThisTwo = new TestThisTwo()
testThisTwo.test()
}
}