IDKWhatImDoing
IDKWhatImDoing

Reputation: 147

Array TypeError

So I am getting a "Uncaught TypeError: Cannot read property '0' of undefined at update" at line 42, which is this one:

init.ctx.moveTo(this.trail[0].x,this.trail[0].y); 

from the following code:

window.onresize = function(){
  init.canvas.width = window.innerWidth;
  init.canvas.height = window.innerHeight;
  //updateComponents();
}
var init = {
  canvas: new Object(),
  ctx: new Object(),
  constructCanvas: function(){
    this.canvas = document.getElementById("canvas");
    this.ctx = this.canvas.getContext("2d");
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
  }
}
init.constructCanvas();

var background = {
  color: "green",
  refresh: function(){
    init.ctx.fillStyle = this.color;
    init.ctx.fillRect(0,0,init.canvas.width,init.canvas.height);
  }
}
//background.refresh();

function updateComponents(){
  background.refresh();
}

function WalkingLine(arguments){
  this.frames = 0;
  this.trail = [];
  this.walkLength = 5;
  this.position = arguments.position;
  this.color = "black";
  this.trail[0] = this.position;
}
WalkingLine.prototype = {
  update: function(){
    init.ctx.beginPath();
    init.ctx.moveTo(this.trail[0].x,this.trail[0].y);    
    var i;
    for(i=1;i<this.trail.length;i++)
      init.ctx.lineTo(this.trail[i].x,this.trail[i].y);
    init.ctx.stroke();
    this.generateNext();
    },
  genarateNext: function(){
    this.trail[this.trail.length] = {x:this.trail[this.trail.length-1].x+5,y:this.trail[this.trail.length-1].y};
    init.ctx.lineTo(this.trail[this.trail.length-1].x,this.trail[this.trail.length-1].y);
    inti.ctx.stroke();
}
};
var one = new WalkingLine({position:{x:100,y:100}});
setTimeout(one.update,1000);

So i dont understand why i am apparently trying to access an invalid index in the array because i explicitly set table[0] in the constructor of the WalkingLine class yet despite that it still says it is an uncaught type Error.

Upvotes: 0

Views: 85

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138557

You lose context:

setTimeout(one.update,1000);

That way you pass only update without the one, so when its called later it does not know where it belongs to. You either need to call it directly ( inside an arrow function):

setTimeout(()=>one.update(),1000);

or you need to bind the function to one:

setTimeout(one.update.bind(one),1000);

Upvotes: 2

Related Questions