在另一个方法中调用原型方法

时间:2019-11-08 05:49:00

标签: javascript

我有两个函数Rectangle.prototype.translate和Rectangle.prototype.moveToTheRight。我正在尝试通过使用this.translate(x,y)在moveToTheRight函数中使用转换函数,但是这无法正常工作,而是出现“ TypeError:this.translate不是函数”。我在做什么错了?

//rectangle object with x,y as starting position
function Rectangle(x,y, width, height){
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

//moves the rectangle object
Rectangle.prototype.translate = function(x,y){
  this.x += x;
  this.y += y;
}

// Moves the rectangle object to the right

Rectangle.prototype.moveToTheRight= function(x){
setInterval(function(){

let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');

  ctx.clearRect(0,0,300,150);
  ctx.fillStyle = 'blue';
  this.translate(x,0);
  ctx.fillRect(this.x,this.y, this.width,this.height);

},1000)
}

0 个答案:

没有答案