首页 > 解决方案 > 在三个 JS 中使用类构造函数

问题描述

我想知道使用 JavaScript 类 inn 三个 js 是否是常见的做法。

我搜索了一些关于这个的意见,大多数人说“使用原型”更常见。

由于我对原型的类构造函数相对更舒服,因此我尝试找到一些使用类而不是原型的示例。(即使原型和类在做几乎相同的工作)。

示例:https ://codepen.io/tksiiii/pen/VOEKLQ

如果我使用类构造函数而不是原型,会有问题或限制吗?我试图做的方法如下。

class ParticleMesh {
    constructor(num, vels, type) {
        this.particleNum = num;
        this.timerStartFading = 10;
        this.mesh = getPointMesh(num, vels, type);
    }
    update(gravity) {
        if (this.timerStartFading > 0) this.timerStartFading -= 0.3;
        const { position, velocity, color, mass } = this.mesh.geometry.attributes;
        const decrementRandom = () => (Math.random() > 0.5 ? 0.98 : 0.96);
        const decrementByVel = v => (Math.random() > 0.5 ? 0 : (1 - v) * 0.1);
        for (let i = 0; i < this.particleNum; i++) {
            const { x, y, z } = getOffsetXYZ(i);
            velocity.array[y] += gravity.y - mass.array[i];
            velocity.array[x] *= friction;
            velocity.array[z] *= friction;
            velocity.array[y] *= friction;
            position.array[x] += velocity.array[x];
            position.array[y] += velocity.array[y];
            position.array[z] += velocity.array[z];
            const { a } = getOffsetRGBA(i);
            if (this.timerStartFading <= 0) {
                color.array[a] *= decrementRandom() - decrementByVel(color.array[a]);
                if (color.array[a] < 0.001) color.array[a] = 0;
            }
        }
        position.needsUpdate = true;
        velocity.needsUpdate = true;
        color.needsUpdate = true;
    }
    disposeAll() {
        this.mesh.geometry.dispose();
        this.mesh.material.dispose();
    }
}

谢谢你。

标签: constructorthree.jsprototype

解决方案


推荐阅读