2014-02-06 3 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); 
} 

대신 methodTwo(function (err) { });를 호출 내가 this.methodTwo(function (err) { }); 모든 것이 잘 작동 호출하면 오류 메시지가 Uncaught TypeError: Cannot read property 'concurrency' of undefined

인을 조롱 할 것인지 여부를 선택하는 기능입니다.

+0

예를 들어 경고 또는 console.log를 추가하고 사용자의 행동이 무엇인지 말할 수 있습니까? –

답변

1
var methodTwo = this.methodTwo; 

가변하는 방법을 할당 할 때, 함수는 문맥 this 손실이 더 이상 원래의 객체를 참조하지 않는다. 이 시도 : 영구적 methodTwo을 무시하지 않으려면

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

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))' –