2014-02-06 96 views
0

我有一个情况,我想模拟一个函数,如果某些条件满足,我收到一个错误。javascript嘲笑原型函数错误

这里是有条件地选择是否嘲笑功能

MyClass.prototype.methodOne = function (callback) { 
    var self = this; 
    var methodTwo = this.methodTwo; 
    if (someCondition) { 
    methodTwo = function(callback) { 
     callback(null); 
    }; 
    } 
    methodTwo(function (err) { }); 
} 

MyClass.prototype.methodTwo = function (callback) { 
    var self = this; 
    var batch = new Batch(); 
    batch.concurrency(this.options.concurrency); ----> error here 
    // some more stuff 
    callback(err); 
} 

的错误消息是Uncaught TypeError: Cannot read property 'concurrency' of undefined

如果不是调用methodTwo(function (err) { });我打电话this.methodTwo(function (err) { });一切正常功能。

+0

您可以在您的示例中添加一些警报或console.log,并说明您的详细行为是什么? –

回答

1
var methodTwo = this.methodTwo; 

当赋值给一个变量的方法,该功能失去其上下文和this不再是指原始对象。试试这个:

MyClass.prototype.methodOne = function (callback) { 
    if (someCondition) { 
    this.methodTwo = function(callback) { 
     callback(null); 
    }; 
    } 
    this.methodTwo(function (err) { }); 
} 

如果你不希望覆盖methodTwo永久使用Function.prototype.bind

MyClass.prototype.methodOne = function(callback) { 
    var methodTwo = this.methodTwo.bind(this); 
    if (someCondition) { 
     methodTwo = function(callback) { 
      callback(null); 
     }; 
    } 
    methodTwo(function(err) { 
    }); 
} 

对于例如,

var o = { 
    a: 'asdf', 
    oMethod: function() { 
    return this.a; 
    } 
}; 

在这里,如果您分配oMethod给一个变量,调用它将导致undefined

var oMethod = o.oMethod; 
oMethod(); //undefined 

var oMethod = o.oMethod.bind(o); 
oMethod(); //asdf 
+0

我不确定他是否想为此实例重写“methodTwo”。 –

+0

谢谢 - 我实际上尝试绑定第一次,但意外绑定它的回调 - doh'methodTwo(function(err){}。bind(this))' –