无法访问类构造函数变量

时间:2019-02-22 14:11:11

标签: javascript reactjs ecmascript-6 constructor

我无法在构造函数本身之外访问构造函数的变量。当我使用各种变量时,我收到“未定义”错误消息。下面是我遇到的代码。

export default class Snail{

constructor(args){

    this.colour = args.colour;
    this.context = args.context;
    this.position = args.position;
    this.snail = new Image();

}

renderInit=async()=>{
    let snailimg = await import (`../images/${this.colour}`);


    this.snail.onload = function(){
        this.context.drawImage(this.snail,this.position.x,this.position.y,65,65);
    }
    this.snail.src = snailimg.default;

}

我要实例化4个Snail对象,然后运行它们的renderInit函数,我相信它可以访问构造函数变量:

let snails = {
snail1: new Snail({colour:'blueSnail.png',context:this.state, position:{
  x:0,
  y:22}}),

snail2: new Snail({colour:'pinkSnail.png',context:this.state, position:{
    x:0,
    y:122}}),

snail3: new Snail({colour:'yellowSnail.png',context:this.state, position:{
    x:0,
    y:222}}),

snail4: new Snail({colour:'cyanSnail.png',context:this.state, position:{
    x:0,
    y:322}}
    )
}

snails.snail1.renderInit();
snails.snail2.renderInit();
snails.snail3.renderInit();
snails.snail4.renderInit();

作为一个更具体的示例,上下文变量是对HTML 2D canvas的引用,使用中断后,我可以在变量中看到该引用,但是应该可以从中访问的drawImage函数返回为undefined({{ }}。请有人可以帮助我确定访问这些内容的正确方法吗?

0 个答案:

没有答案