如何在es6中共享多个js文件中的数据
how to share data from multiple js files in es6?
我正尝试着在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。
或者非常懒惰的方法是使你想要共享的对象全局(尽管有些人可能会说不要,这取决于你计划运行的上下文和应用程序的性能需求)
相关文章:
- JS文件的路径正在消失
- 我的外部js文件无法加载
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- 动态加载和卸载js文件
- 如何将变量传递到另一个js文件
- 如何将所有JS文件连接到一个文件夹中
- 从Chrome扩展名中的popup.html文件在background.js文件中运行一个函数
- 如何使用php文件中的GET来获取我在.js文件中声明的变量
- 如何将模板中的标记脚本移动到.js文件中
- 什么's是连接供应商js文件的最佳方式
- 如何在定义js文件后为外部javascript文件设置变量
- 如何在JS文件中获取资源(.resx)字符串
- 将*.js文件的内容放入Object中
- 如何从onclick函数设置全局变量并将其传递给另一个JS文件
- 导致内容安全策略(CSP)冲突错误的本地jquery.js文件
- 如何使用Gmail运行.js文件
- 如何定义一个模块并使用它来分离js文件
- Angular JS文件上传到托管服务器
- 如何引用HTML中节点模块中的js文件
- 如何将JS文件从其他文件夹链接到页面