1

私はnode.jsとexpress.jsを使用しており、./route/users.js内に次の行があります:

exports.add = function(req, res) {
   // some code here
    this.list();
}

exports.delete = function(req, res) {
    // some code here
    this.list();
}


exports.list = function(req, res) {
    // some code here
}

問題は this.list() が機能しないことです。私が得るのは次のエラーです: TypeError: Object # has no method 'list'

私も別のアプローチを試しました:

module.exports = {
  add: function(req, res) {
    // some code here
    this.list();
  },

  delete: function(req, res) {
    // some code here
    this.list();
  },

  list: function(req, res) {
    // some code here
    this.list();
  }
}

しかし、うまくいきませんでした.. ところで、list() 呼び出しでそのエラーを無視する場合、ルートを記述する正しい方法はどれですか?

4

1 に答える 1

0

1 つのオプションはlist、ローカルとして定義して参照し、それをエクスポートすることです。また、 を呼び出すときに、おそらくreqandを渡したいことにも注意してください。reslist()

function list(req, res) {
  // ...
}

module.exports = {
  add: function add(req, res) {
    // ...
    list(req, res);
  },

  delete: function (req, res) {
    // ...
    list(req, res);
  },

  list: list
};

使用の問題は、オブジェクトthisに関連付けられていないことです。within anyexportsの値は、その関数がどのように定義されたかではなく、その関数がどのように呼び出されたかによって異なります。thisfunction

于 2013-07-08T22:20:24.437 に答える