2016-03-05 13 views
6

としてパス機能は、このクラスは、私のexpressjsアプリケーション内のすべてのコントローラを拡張するために使用されています。あなたは私が作った、自動的にセットアップするには、「登録」の方法を見ることができるようにES6クラス、パラメータ

import response from '../utils/responseParser.js'; 

const APISLUG = '/api/v1/'; 

export default class BaseController { 

    constructor(name, app, model){ 
    this.model = model; 
    this.app = app; 
    this.name = name; 
    console.log(model); 
    this.register(); 
    } 

    register() { 
    this.app.get(APISLUG + this.name, this.all); 
    } 
    /* 
    Retrive all records 
    */ 
    all(req, res, next) { 
    this.model.all(req.body, (err, data) => { 
     if(err) return res.json(response.replyError(data)); 
     return res.json(response.reply(data)); 
    }); 
    } 
} 

すべて基本ルート。

私は、この行のエラーunable to read property " model " of undefined "を得る:

this.app.get(APISLUG + this.name, this.all); 

私はこれは私がパラメータとして関数を渡す際にスコープが失われるという事実によるものであると信じています。これをどうすれば解決できますか?

答えて

11

使用bind方法は、あなたがクラスのプロパティとして矢印機能を設定することができ、この

this.app.get(APISLUG + this.name, this.all.bind(this)); 
+0

ありがとうございました!できます。 –

+0

あなたは大歓迎です:) –

+0

'.bind(this)'は魔法です、ありがとう! – Robula

3

のように、スコープをバインドします。矢印機能は、thisの値(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)に語彙的にバインドします。あなたの例では

:クラス上の機能を矢印

export default class BaseController { 
    ... 
    all = (req, res, next) => { // This is the only line that changed 
    ... 
    } 
} 

注標準ES6構文ではありませんが、おそらく(ここではコメント欄でそれについていくつかの注意事項:https://stackoverflow.com/a/31362350/2054731)ES7が付属しています。このES7機能や他のES7機能を使用できるようにプロジェクトを設定する必要があるかもしれません。