简体   繁体   English

如何使 JavaScript class 可用于任何项目

[英]how to make JavaScript class portable for any project

I have this code and I always have to creat the const ctx at begin of document with same name used in the class, and I wonder if have way make this class more portable for others project我有这段代码,我总是必须在 class 中使用的相同名称的文档开头创建 const ctx,我想知道是否有办法让这个 class 对其他项目更具可移植性

const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');

class layer{
    constructor(image, speedModifier){
        this.x = 0;
        this.y = 0;
        this.width = 2400;
        this.height = 700;
        //this.x2 = this.width;
        this.image = image;
        this.speedModifier = speedModifier;
        this.speed = gameSpeed * this.speedModifier
    }
    update(){
        this.speed = gameSpeed * this.speedModifier;
        this.x = gameFrame * this.speed % this.width;
    }
    draw(){
        ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
        ctx.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
    }
}

Just export your class and make your class take in a context in the constructor.只需导出您的 class 并让您的 class 接受构造函数中的上下文。

export class Layer {
  constructor(image, speedModifier, context) {
    this.context = context;
    this.x = 0;
    this.y = 0;
    this.width = 2400;
    this.height = 700;
    this.image = image;
    this.speedModifier = speedModifier;
    this.speed = gameSpeed * this.speedModifier
  }

  draw(){
    this.context.drawImage(this.image, this.x, this.y, this.width, this.height);
    this.context.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
  }
}

Now anyone who uses your class can import it:现在任何使用您的 class 的人都可以导入它:

import { Layer } from './layer.js';

And the user of the class has to get the canvas context. class 的用户必须获取 canvas 上下文。 However they can then get that once and pass it in to as many layers as they want:然而,他们可以获得一次并将其传递给他们想要的任意多个层:

const context = document.querySelector('canvas').getContext('2d');
const layer1 = new Layer(someImage, 1, context);
const layer2 = new Layer(anotherImage, 1, context);
const layer3 = new Layer(thirdImage, 2, context);

Nothing more you can really do beyond that.除此之外,您无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM