uniapp如何定义类
定义类的基本语法
在 UniApp 中定义类与标准 JavaScript/TypeScript 语法一致,可以使用 class 关键字。以下是一个基础示例:
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
greet() {
console.log(`Hello, my name is ${this.name}`)
}
}
类的继承
通过 extends 实现继承,子类可以继承父类的属性和方法:
class Student extends Person {
constructor(name, age, grade) {
super(name, age)
this.grade = grade
}
study() {
console.log(`${this.name} is studying in grade ${this.grade}`)
}
}
静态属性和方法
使用 static 关键字定义静态成员,这些成员属于类本身而非实例:
class MathUtils {
static PI = 3.14159
static add(a, b) {
return a + b
}
}
Getter/Setter
通过 getter 和 setter 控制对属性的访问:
class Temperature {
constructor(celsius) {
this._celsius = celsius
}
get celsius() {
return this._celsius
}
set celsius(value) {
if (value < -273.15) {
throw new Error('Temperature below absolute zero')
}
this._celsius = value
}
}
私有字段
ES2022 引入的私有字段语法,字段名前加 # 表示私有:
class Counter {
#count = 0
increment() {
this.#count++
}
get value() {
return this.#count
}
}
在 UniApp 中使用类
在 UniApp 的 Vue 组件中,可以在 <script> 部分定义和使用类:
<script>
class Product {
constructor(name, price) {
this.name = name
this.price = price
}
}
export default {
data() {
return {
product: new Product('iPhone', 999)
}
}
}
</script>
TypeScript 支持
如果使用 TypeScript,可以添加类型注解:
class Point {
x: number
y: number
constructor(x: number, y: number) {
this.x = x
this.y = y
}
}






