定義一個類
class Person {
name: string;
constructor(name: string) {
this.name = name
}
run(): void {
console.log(this.name + '在運動')
}
getNane():string {
return this.name
}
setName(name: string):void {
this.name = name
}
}
var p = new Person('李狗蛋')
p.run()
p.getNane()
p.setName('張翠花')
繼承
class Person {
name: string
constructor(name: string) {
this.name = name
}
run(): void {
console.log(this.name + '在運動')
}
}
class Student extends Person {
constructor(name: string) {
super(name)
}
work(): void {
console.log(this.name + '在工作')
}
run(): void {
console.log(this.name + '在運動')
}
}
var s = new Student('趙鐵柱')
s.run()
s.work()
類裏面的修飾符
class Person {
public name: string
constructor(name: string) {
this.name = name
}
run(): void {
console.log(this.name)
}
}
class Student extends Person {
constructor(name: string) {
super(name)
}
log(): void {
console.log(this.name)
}
}
let p = new Person('李狗蛋')
console.log(p.name)
let s = new Student('張翠花')
s.log()
class Person {
protected name: string
constructor(name: string) {
this.name = name
}
run(): void {
console.log(this.name)
}
}
class Student extends Person {
constructor(name: string) {
super(name)
}
log(): void {
console.log(this.name)
}
}
let p = new Person('李狗蛋')
console.log(~~p.name~~ )
let s = new Student('張翠花')
s.log()
class Person {
private name: string
constructor(name: string) {
this.name = name
}
run(): void {
console.log(this.name)
}
}
class Student extends Person {
constructor(name: string) {
super(name)
}
log(): void {
console.log(~~this.name~~ )
}
}
let p = new Person('李狗蛋')
p.run()
console.log(~~p.name~~ )
let s = new Student('張翠花')
s.log()
類裏面的靜態屬性和方法
class Person {
name: string
static code: number = 1
constructor(name: string) {
this.name = name
}
run(): void {
console.log(this.name)
}
static print(): void {
console.log('靜態方法' + ~~this.name~~ )
console.log('靜態方法' + Person.code)
console.log('靜態方法')
}
}
console.log(Person.code)
Person.print()
多態:多態屬於繼承
class Animal {
name: string
constructor(name: string) {
this.name = name
}
eat(food: string): void {
console.log(`${this.name}喫${food}`)
}
}
class Dog extends Animal {
constructor(name: string) {
super(name)
}
}
let dog = new Dog('小黑')
dog.eat('狗糧')
class Cat extends Animal {
constructor(name: string) {
super(name)
}
eat(food: string): void {
console.log(`${this.name}喫${food},喝水`)
}
}
let cat = new Cat('小花貓')
cat.eat('貓糧')
typescript中的抽象類
abstract class Animal {
name: string
constructor(name: string) {
this.name = name
}
abstract eat(): void
}
class Dog extends Animal {
constructor(name: string) {
super(name)
}
eat(): void {
console.log(this.name + '喫東西')
}
}
let dog = new Dog('小黑')
dog.eat()