2015-01-04 4 views
0

개체를 만들 때 즉시 액세스하려고 시도하는 메서드 here을 사용하면 클래스 메서드는 개체가 만들어졌지만 액세스 할 수 없습니다. Node.js에서 OOP를 왜곡하고 비동기식으로 만들 수 있습니까? (I 차단 것에 대해 너무 걱정하지 않아요 ...이 하지) 거의 cronjob에 같은 (다른 액세스 할 수있는 스크립트)비동기식 모듈

가 코드 수정 : 나는라면

// Constructor 
function Foo(bar, callback) { 
    // always initialize all instance properties 
    this.bar = bar; 
    this.baz = 'baz'; // default value 
    callback(); 
} 
// class methods 
Foo.prototype.fooBar = function() { 
    return this.bar; 
}; 
// export the class 
module.exports = Foo; 

을 시도하고이

var p1; 
var p2; 
async.series([ 
    function(callback){ 
     new Foo("Foobar1", function(){ 
      p1 = this; 
      callback(null, 'one'); 
     }); 
    }, 
    function(callback){ 
     new Foo("Foobar2", function(){ 
      p2 = this; 
      callback(null, 'two'); 
     }); 
    } 
], 
// optional callback 
function(err, results){ 
    // results is now equal to ['one', 'two'] 
    console.log(p1); // this produces *something*, therefore its set 
    console.log(p1.fooBar()); // nope! 
}); 

내가 TypeError: Object #<Object> has no method 'fooBar'

를하고있는 중이 야 무엇을 얻을 잘못을 저글링 비동기 하는가? 비동기식으로 처리하려면 어떻게해야합니까?

답변

0

이것은 비동기와는 아무런 관련이 없습니다. 이것은 약 this에 대한 것이 아닙니다.

콜백 내에서 this은 아무 것도 바인딩되지 않으므로 use strict에 따라 글로벌 노드 객체 또는 null입니다.

생성자에서 callback.call(this)을 시도하십시오.