2016-03-05 107 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语法,但可能会配备ES7(有关的一些注意事项在这里评论:https://stackoverflow.com/a/31362350/2054731)。您可能需要配置您的项目才能使用此功能和/或其他ES7功能。