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'を呼び出していますか? – Timo

+0

これはHapiルートハンドラから呼び出されます。https://hapijs.com/tutorials/routing – cusejuice

+0

この種の問題では、通常、呼び出しに '.bind(this)'がありません。 –

答えて

3

OUはthisは、常にコンストラクタにmakeRequestbind its contextにインスタンスを指すようにしたい:

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

Hmですが、ここで何か不足していますか?私は、新しいES6クラスのキーワードを使って 'this'がすぐに使えると思っていました。ですから、基本的には、クラスのすべてのメソッドが 'this'への参照を取得するために、コンストラクタでそのコンテキストをバインドする必要がありますか?奇妙だと思われる – cusejuice

+2

いいえ、クラスはJavaScriptでメンバー関数のオートバインドを実行しません。 – Timo

+2

'class'は、JSが長年にわたって持っていたプロトタイプベースの継承のほとんどが文法上の砂糖です。 「この」セマンティクスと他のほとんどの動作は同じです。 – noppa

関連する問題