如何在es6中共享多个js文件中的数据

how to share data from multiple js files in es6?

本文关键字:js 文件 数据 共享 es6      更新时间:2023-09-26

我正尝试着在ES6上创造一款游戏。我已经制作了多个文件。一个主文件,我从不同的对象收集所有的信息,一个文件,我要做一个角色和一个文件,具有画布属性。

问题是:文件walter.es6有一个将从左向右移动的正方形。所以我开始draw();在script.es6(主文件)中的walter.es6。但是walter.es6文件需要canvas.es6文件中的ctx。

我想这是因为walter.es6不知道canvas.es6的存在。但是为了保持代码的整洁,他们没有必要互相认识(这是之前告诉我的)。需要有另一种解决方案,以便walter.es6了解CTX的主要功能。但如何?

我希望有人能帮助我。提前谢谢你。

这是我一直在谈论的文件:

script.es6

    const WalterPlayer = require('./walter.es6')
    const DeaEnemy = require('./dea.es6')
    const Wereld = require('./level.es6')
    const Canvas = require('./canvas.es6')

    class Hoofdclass {
        constructor() {
            this.walter = new WalterPlayer();
            this.enemy = new DeaEnemy();
            this.wereld = new Wereld();
            this.canvas = new Canvas();
            this.draw();
        }
        draw(){
            this.walter.draw();
            //alles in beweging zetten
            window.requestAnimationFrame(this.draw.bind(this));
    }
    }
    document.addEventListener("DOMContentLoaded", function(event) {
        let t = new Hoofdclass();
    });

walter.es6

class Walter {
    constructor() {
        this.x = 250;
        this.y = 200;
        this.height = 10;
        this.width = 10;
        console.log(this.canvas)
    }
    draw(){
         this.ctx.clearRect(0,0,500,400)
         this.ctx.beginPath();
         this.x += 1;
         this.y += 0.25;
         this.ctx.fillRect(this.x, this.y, this.height, this.width);
         this.ctx.closePath();
    }
}
module.exports = Walter;

canvas.es6

class Canvas {
    constructor(c, ctx) {
        this.c = document.getElementById("canvas");
        this.ctx = this.c.getContext("2d");
        console.log("pieppiep")
    }
}
module.exports = Canvas;

将需要的对象传递给需要它的对象。在实例化时,或根据需要。

根据需要eg

this.walter.draw(this.canvas.ctx); // in draw loop

和在walter。

draw(ctx){
     ctx.clearRect(0,0,500,400);
     ... etc

或实例化

this.walter = new WalterPlayer(this.canvas.ctx); // instantiation

和构造函数

class Walter {
    constructor(ctx) {
         this.ctx = ctx;

显然,您需要在画布之后创建Walter。

或者非常懒惰的方法是使你想要共享的对象全局(尽管有些人可能会说不要,这取决于你计划运行的上下文和应用程序的性能需求)