如何在javascript中将原型方法作为回调发送?

时间:2012-07-26 16:53:29

标签: javascript callback this box2d

我有原型方法,它是由我正在使用的Box2D API的回调激活的。回调可以到达函数,但它不是函数的正确实例。获取回调以调用 .prototype类的正确语法是什么。

对Box2D API的调用:

Box2d.prototype.getBodyAtMouse = function() {
   this.mousePVec = new this.b2Vec2(this.mouseX/this.SCALE, this.mouseY/this.SCALE);
   var aabb = new this.b2AABB();
   aabb.lowerBound.Set(this.mouseX/this.SCALE - 0.001, this.mouseY/this.SCALE - 0.001);
   aabb.upperBound.Set(this.mouseX/this.SCALE + 0.001, this.mouseY/this.SCALE + 0.001);
   this.selectedBody = null;
   var _this = this; 
   this.world.QueryAABB(_this.getBodyCB, aabb);
   return this.selectedBody;

}

这是名为的box2D API方法:

b2World.prototype.QueryAABB = function (callback, aabb) {
  var __this = this;
  var broadPhase = __this.m_contactManager.m_broadPhase;

  function WorldQueryWrapper(proxy) {
     return callback(broadPhase.GetUserData(proxy));
  };
  broadPhase.Query(WorldQueryWrapper, aabb);

}

这是我希望API能够正确引用的回调:

Box2d.prototype.getBodyCB = function(fixture) 
{
  if(fixture.GetBody().GetType() != this.b2Body.b2_staticBody) {
   if(fixture.GetShape().TestPoint(fixture.GetBody().GetTransform(), this.mousePVec)) {
      selectedBody = fixture.GetBody();
      return false;
   }
}
return true;

}

1 个答案:

答案 0 :(得分:0)

使用

var _this = this; 
this.world.QueryAABB(function(fix){
   _this.getBodyCB(fix);
}, aabb);

this.world.QueryAABB(this.getBodyCB.bind(this), aabb);

(旧版浏览器不支持which,但可以轻松修补)