class User {
public name: string
public age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
public getName() {
return `name: ${this.name}, age: ${this.age}`
}
}
const user1 = new User("whbbit", 25)
user1.name = "wxw"
console.log(user1.name)
console.log(user1.getName())
class User {
protected name: string
protected age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
protected show() {
console.log("show")
}
public getName() {
return `name: ${this.name}, age: ${this.age}`
}
}
const user1 = new User("whbbit", 25)
user1.name = "wxw" // ts 报错
console.log(user1.name) // ts 报错
user1.show() // ts 报错
console.log(user1.getName()) // 正常运行
在父类中声明的受保护的方法或属性,在子类中可以调用。但在类外部不可调用
ts
class Person {
protected name: string
protected age: number
protected show() {
console.log("show")
}
}
class User extends Person {
constructor(name: string, age: number) {
super()
this.name = name
this.age = age
}
public getInfo() {
return this.show()
}
}
const user1 = new User("wxw", 25)
user1.getInfo()
class Axios {
readonly site: string = "https://www.weilog.me/api"
constructor() {}
public get(url: string) {
console.log(`请求地址是${url}`)
return []
}
}
const instance = new Axios()
console.log(instance.site)
instance.site = "https://api.com" // 报错:Cannot assign to 'site' because it is a read-only property
但是在构造函数初始化时可以更改
ts
class Axios {
readonly site: string = "https://www.weilog.me/api"
constructor(site?: string) {
this.site = site || this.site
}
public get(url: string) {
console.log(`请求地址是${this.site}/${url}`)
return []
}
}
const instance = new Axios()
instance.get("article") // "请求地址是https://www.weilog.me/api/article"
const instance1 = new Axios("https://www.weilog.me/docs")
instance1.get("article") // "请求地址是https://www.weilog.me/docs/article"
class User {
constructor(public name: string, public age: string) {}
// 等同于
// public name: string
// public age: number
// constructor( name: string, age: number) {
// this.name = name
// this.age = age
// }
}
class User {
constructor(private _name: string) {}
public get name(): string {
return this._name
}
public set name(name: string) {
this._name = name
}
}
const user = new User("wxw")
console.log(user.name)
console.log((user.name = "whbbit"))
console.log(user.name)
评论区
评论加载中...