Javascript 在回调中调用函数时出现作用域问题

Javascript 在回调中调用函数时出现作用域问题,javascript,canvas,html5-canvas,easeljs,createjs,Javascript,Canvas,Html5 Canvas,Easeljs,Createjs,在画布内单击时,它将生成一个球并移动到单击的位置 当球到达它的位置时,我希望它自己移动。但我想我有个问题 调用removeBall()函数时使用范围 您可以在她身上找到一个工作示例: /* *主应用程序逻辑 */ 函数Main(){ this.canvas=“canvas”; this.stage=null; 这个宽度=0; 这个高度=0; this.init(); } Main.prototype.init=函数(){ console.clear(); this.stage=newcreate

在画布内单击时,它将生成一个球并移动到单击的位置 当球到达它的位置时,我希望它自己移动。但我想我有个问题 调用removeBall()函数时使用范围

您可以在她身上找到一个工作示例:

/*
*主应用程序逻辑
*/
函数Main(){
this.canvas=“canvas”;
this.stage=null;
这个宽度=0;
这个高度=0;
this.init();
}
Main.prototype.init=函数(){
console.clear();
this.stage=newcreatejs.stage(this.canvas);
这是resize();
//开始游戏循环
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener(“tick”,this.gameLoop);
//单击事件处理程序
this.stage.on(“stagemousedown”,函数(evt){
主火球(evt);
});
};
Main.prototype.fireBall=函数(evt){
var bal=新的bal(evt.stageX,evt.stageY);
};
Main.prototype.resize=函数(){
//调整画布的大小,使其具有最大宽度
this.WIDTH=window.innerWidth;
this.HEIGHT=数学地板(window.innerWidth*9/16);
this.stage.canvas.width=this.width;
this.stage.canvas.height=this.height;
};
Main.prototype.gameLoop=函数(){
//游戏循环
main.stage.update();
};
/*
*球逻辑
*/
功能Bal(毒素、玩具){
this.toX=toX;
这个玩具=玩具;
这个.widthPerc=8;
this.init();
}
Bal.prototype.width=函数(){
返回Math.floor(main.stage.canvas.width/100*this.widthPerc);
};
Bal.prototype.init=函数(){
//创建一个新球
this.ball=new createjs.Shape();
this.ball.graphics.beginull(“绿色”).drawCircle(0,0,this.width());
this.ball.x=(main.stage.canvas.width/2)-(this.width()/2);
this.ball.y=main.stage.canvas.height-20;
main.stage.addChild(this.ball);
这个。移动();
};
Bal.prototype.move=函数(){
//创建一个裁剪坐标的二者之间
createjs.Tween.get(this.ball).to({
x:这是toX,
y:这个玩具,
scaleX:0.4,scaleY:0.4,
轮换:180
},
750,//速度
createjs.Ease.none

).call(this.removeBall);//确定找到了解决方案!使用bind()功能

Bal.prototype.move = function() {
  console.log(this.toX +","+this.toY);
  createjs.Tween.get(this.ball).to({
      x: this.toX ,
      y: this.toY ,
      scaleX:0.4,scaleY:0.4,
      rotation: 180
    },
    750, //speed
    createjs.Ease.none
  ).call(this.removeBall.bind(this));
};

上面使用bind的解决方案是可行的,但是有一个更好的解决方案。bind并不是在所有浏览器中都可用(最著名的是Safari 5.1,它是一款现代浏览器)

TweenJS在使用
call()
时内置了对作用域函数的支持。只需将作用域作为第三个参数传递即可

Ball.prototype.move = function() {
  console.log(this.toX +","+this.toY);
  createjs.Tween.get(this.ball).to({
      x: this.toX ,
      y: this.toY ,
      scaleX:0.4,scaleY:0.4,
      rotation: 180
    },
    750, //speed
    createjs.Ease.none
  ).call(this.removeBall, null, this);
};
还可以将函数参数数组作为第二个参数传递

Tween.call(this.removeBall, [this.ball], this);

animationDone
根本不在你的问题中。我的错,修正了错误。
Tween.call(this.removeBall, [this.ball], this);