我在nodejs中使用JSON-RPC庫。我按名稱註冊我的函數(例如rpc({publicName: privateFunction})
),RPC lib爲我調用函數,並處理編組JSON和函數參數。它適用於簡單的函數,但當它傳遞一個原型函數(一個在對象的原型鏈上定義的函數)時會中斷。問題是RPC lib正在調用使用apply
的函數,該函數改變了this
的上下文,因此我無法再訪問其他原型屬性/函數。JS原型函數'this'混淆
這是問題的一個例子:
var MyObj = function(prop1,prop2,prop3){
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
}
MyObj.prototype.showProps = function(separator){
console.log(this.prop1 + separator + this.prop2 + separator + this.prop3);
}
var myObjInstance = new MyObj('a', 'b', 'c');
myObjInstance.showProps(',');
// displays a,b,c
// I register the function as rpc({show_props:myObjInstance.showProps}) and the RPC lib calls it like
myObjInstance.showProps.apply(this, [',']);
// displays undefined,undefined,undefined
是否有更好的方法來解決這一問題?有沒有辦法在原型函數內部保留this
的上下文?
它是可用的NodeJS。 – pimvdb
Luv it!完美的作品。謝謝! – jckdnk111