2012-07-26 63 views
0

我有一個由我使用的Box2D API的回調激活的原型方法。回調可以到達函數,但它不是函數的正確實例。什麼是正確的語法來獲得回調調用。原型類。如何發送原型方法作爲JavaScript中的回調?

的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; 

}

回答

0

要麼使用

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

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

which不被舊版本瀏覽器的支持,但很容易被墊高)

相關問題