2

방금 ​​클래스와 비동기를 실험하기 시작했습니다. 노드 버전 8.9.0 (LTS)을 사용하고 있습니다. 내가 console.log(this) 일 때 개체에 대한 참조 대신 undefined이 표시됩니다.클래스/비동기 사용시 정의되지 않은 "this"얻기

subhandler.js Y 경우

class Handler { 
    constructor(props) { 
    this.defaultRes = { 
     data: successMessage, 
     statusCode: 200 
    }; 
    } 

    async respond(handler, reply, response = this.defaultRes) { 
    console.log(this); // why is `this` undefined???? 
    try { 
     await handler; 
     return reply(response.data).code(response.statusCode) 
    } catch(error) { 
     return reply(error); 
    } 
    } 
} 

class SubHandler extends Handler { 
    constructor(props) { 
    super(props); 
    this.something = 'else'; 
    } 

    makeRequest(request, reply) { 
    console.log(this); // why is `this` undefined!! 
    // in this case, doSomeAsyncRequest is a promise 
    const handler = doSomeAsyncRequest.make(request.params); 
    super.respond(handler, reply, response); 
    } 
} 

module.exports = new SubHandler; 

내부 그러면 동상 경로

const SubHandler = require('./subhandler'); 

server.route({ 
    method: 'GET', 
    path: '/', 
    handler: SubHandler.makeRequest, 
    // handler: function (request, reply) { 
    // reply('Hello!'); //leaving here to show example 
    //} 
}); 

원형 예

function Example() { 
    this.a = 'a'; 
    this.b = 'b'; 
} 

Example.prototype.fn = function() { 
    console.log(this); // this works here 
} 

const ex = new Example(); 
ex.fn(); 
+0

가 어떻게'makeRequest'를 호출 : OU는 this 항상 생성자 bind its context, makeRequest에서 인스턴스를 가리 키도록 싶어? – Timo

+0

Hapi 라우트 핸들러에서 호출됩니다. https://hapijs.com/tutorials/routing – cusejuice

+0

이런 종류의 문제에 대해서는 일반적으로 호출에'.bind (this) '가 없습니다. –

답변

3

class SubHandler extends Handler { 
    constructor(props) { 
    super(props); 

    this.makeRequest = this.makeRequest.bind(this) 

    this.something = 'else'; 
    } 

    makeRequest(request, reply) { 
    console.log(this); 
    const handler = doSomeAsyncRequest.make(request.params); 
    super.respond(handler, reply, response); 
    } 
} 
+0

흠이 아닙니다. 작동하지만 여기에 뭔가 빠졌습니까? 나는이 새로운 ES6 클래스 키워드를 사용하여 out-of-the-box에서 작동 할 것이라고 생각했다. 그래서 기본적으로, 클래스의 모든 메소드가 'this'에 대한 참조를 얻으려면 컨스트럭터에서 컨텍스트를 바인딩해야합니까 ?? 이상하게 보입니다. – cusejuice

+2

아니요, 클래스는 JavaScript에서 멤버 함수를 자동 바인드하지 않습니다. – Timo

+2

'class'는 JS가 오래 동안 가지고 있던 프로토 타입 기반 상속에 대한 대부분의 문법적인 설탕입니다. '이'의미론과 다른 대부분의 행동은 여전히 ​​동일합니다. – noppa

관련 문제