uniapp如何定义类
定义类的基本语法
在UniApp中,可以使用ES6的类语法来定义类。类可以包含构造函数、属性和方法。
class MyClass {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}`);
}
}
类的继承
UniApp支持类的继承,使用extends关键字实现。
class ParentClass {
constructor(name) {
this.name = name;
}
}
class ChildClass extends ParentClass {
constructor(name, age) {
super(name);
this.age = age;
}
}
静态方法和属性
类中可以定义静态方法和属性,通过类名直接访问。
class Utils {
static version = '1.0.0';
static formatDate(date) {
return date.toLocaleDateString();
}
}
类的Getter和Setter
可以使用getter和setter来控制属性的访问。
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(name) {
[this.firstName, this.lastName] = name.split(' ');
}
}
类的私有字段
ES2022引入了私有字段语法,字段名前加#表示私有。
class Counter {
#count = 0;
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
类与UniApp组件结合
在UniApp的Vue组件中,可以将类实例作为组件的属性使用。
import MyClass from './MyClass.js';
export default {
data() {
return {
myInstance: new MyClass('UniApp')
}
}
}






