下面我将为你详细解释如何在小程序中创建和使用类,并附上完整的代码示例。

核心要点
- 位置:类的定义通常放在一个单独的
.js文件中,以便于管理和复用。 - 语法:使用标准的 ES6
class语法。 - 使用:在需要使用这个类的页面(Page)或另一个类中,通过
require引入该.js文件,然后创建类的实例。
创建一个类文件
我们在项目的 utils 文件夹(如果没有可以自己创建一个)下创建一个新的文件,product.js,这个文件将用来定义我们的“产品”类。
文件路径: utils/product.js
// utils/product.js
// 使用 class 关键字定义一个 Product 类
class Product {
// 1. 构造函数 constructor
// 当使用 new Product() 创建实例时,这个函数会被自动调用
constructor(id, name, price) {
this.id = id; // 产品ID
this.name = name; // 产品名称
this.price = price; // 产品价格
this.createdAt = new Date(); // 创建时间
}
// 2. 实例方法
// 定义在类的原型上,每个实例都可以调用
getInfo() {
return `产品: ${this.name}, 价格: ¥${this.price.toFixed(2)}`;
}
// 定义一个可以修改价格的方法
setPrice(newPrice) {
if (newPrice > 0) {
this.price = newPrice;
console.log(`${this.name} 的价格已更新为 ¥${newPrice}`);
} else {
console.log('价格必须大于 0');
}
}
// 3. 静态方法 static
// 定义在类本身上,而不是实例上,通过类名直接调用
static comparePrice(productA, productB) {
if (productA.price > productB.price) {
return `${productA.name} 更贵`;
} else if (productA.price < productB.price) {
return `${productB.name} 更贵`;
} else {
return '两者价格相同';
}
}
}
// 4. 导出类
// 使用 module.exports 将这个类导出,以便其他文件可以引入使用
module.exports = Product;
代码解释:
constructor: 构造函数,用于初始化新创建的对象。this: 指向当前实例对象。getInfo(),setPrice(): 这些是实例方法,你需要先创建类的实例(new Product()),然后才能调用这些方法(如product.getInfo())。static comparePrice(): 这是一个静态方法,它不依赖于任何实例,而是直接作用于类本身,调用方式是Product.comparePrice(...),而不是instance.comparePrice(...)。module.exports = Product: 这是 CommonJS 的模块导出语法,让product.js文件可以被其他文件require。
在页面中使用这个类
我们创建一个页面(pages/index/index),在这个页面的 JavaScript 文件中引入并使用我们刚刚创建的 Product 类。

文件路径: pages/index/index.js
// pages/index/index.js
// 1. 引入我们刚刚创建的 Product 类
// 路径是相对于当前文件的位置
const Product = require('../../utils/product.js');
Page({
data: {
productList: [], // 用于存放产品实例的数组
comparisonResult: '' // 用于存放价格比较的结果
},
onLoad: function (options) {
// 2. 创建类的实例
const product1 = new Product(1, 'iPhone 15', 5999);
const product2 = new Product(2, '华为 Mate 60', 6999);
const product3 = new Product(3, '小米 14', 4299);
// 3. 调用实例方法
console.log(product1.getInfo()); // 输出: 产品: iPhone 15, 价格: ¥5999.00
product2.setPrice(6899); // 输出: 华为 Mate 60 的价格已更新为 ¥6899
// 4. 调用静态方法
// 注意:静态方法是通过类名直接调用的,不是通过实例
const result = Product.comparePrice(product1, product3);
console.log(result); // 输出: 华为 Mate 60 更贵 (因为 product2 和 product3 的价格比较)
const result2 = Product.comparePrice(product1, product3);
console.log(result2); // 输出: iPhone 15 更贵
// 5. 将实例存储到 data 中,以便在页面上显示
this.setData({
productList: [product1, product2, product3],
comparisonResult: `比较结果: ${result2}`
});
},
// 页面上可以绑定一个方法来触发某些操作
onShowProductInfo: function(e) {
const index = e.currentTarget.dataset.index;
const product = this.data.productList[index];
wx.showToast({
title: product.getInfo(),
icon: 'none'
});
}
});
文件路径: pages/index/index.wxml
<!-- pages/index/index.wxml -->
<view class="container">
<view class="title">产品列表</view>
<view class="product-list">
<view
wx:for="{{productList}}"
wx:key="id"
class="product-item"
bindtap="onShowProductInfo"
data-index="{{index}}"
>
<view class="product-name">{{item.name}}</view>
<view class="product-price">¥{{item.price}}</view>
</view>
</view>
<view class="comparison-result">
{{comparisonResult}}
</view>
</view>
文件路径: pages/index/index.wxss
/* pages/index/index.wxss */
.container {
padding: 20px;
}{
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
}
.product-list {
border: 1px solid #eee;
border-radius: 8px;
overflow: hidden;
}
.product-item {
padding: 15px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
}
.product-item:last-child {
border-bottom: none;
}
.product-name {
font-size: 16px;
}
.product-price {
color: #e64340;
font-weight: bold;
}
.comparison-result {
margin-top: 20px;
padding: 10px;
background-color: #f0f0f0;
border-radius: 4px;
text-align: center;
}
- 定义类:在
.js文件中使用class关键字定义,包含构造函数、实例方法和静态方法。 - 导出类:使用
module.exports = ClassName将类导出。 - 引入类:在需要使用的页面(或其他模块)中,使用
const ClassName = require('path/to/class.js')引入。 - 创建实例:使用
new ClassName()创建类的实例。 - 调用方法:
- 调用实例方法:
instance.method() - 调用静态方法:
ClassName.staticMethod()
- 调用实例方法:
通过这种方式,你可以将复杂的逻辑封装成类,让你的代码结构更清晰、更易于维护和复用,这对于开发稍微复杂一点的小程序非常有帮助。

