2016-09-01 30 views
-1

這是我的對象功能不是一個函數

以下是我是多麼想傳遞參數給其他文檔get函數。

var Controller = require('../Controller.js'); 
Controller.get(arg1, arg2); 

然而nodejs拋出'TypeError:Controller.get不是函數',我在這裏做錯了什麼?謝謝

+4

'步步高控制器'不同於'Controller' – thefourtheye

+1

另外,要正確使用'this',函數必須用'new'調用。 – thefourtheye

+0

@thefourtheye這是我的錯誤忘記改變這一點。現在編輯我的問題。這不是我的錯誤。 :) – garenyondem

回答

3

該代碼有幾個問題,但它不會導致您描述的TypeError: Controller.get is not a function

你打電話給你的匿名函數創建Controller的方式意味着它內部的this將是全局對象(鬆散模式)或undefined(嚴格模式)。讓我們假設寬鬆模式,因爲你沒有說你得到一個錯誤,指定getundefined。這意味着你正在創建一個名爲get全局函數。這也意味着Controller返回全局對象。

這些都不是好東西。 :-)

如果你要導出的對象與get功能,你不需要做任何事情幾乎如此複雜:

var Controller = { 
    get: function (req, res) { 
     res.send({ 
      success: 'you got me' 
     }); 
    } 
}; 
module.exports = Controller; 

或許

function get() { 
    res.send({ 
     success: 'you got me' 
    }); 
} 

module.exports = { get: get }; 

由於這是在NodeJS模塊的上下文中,它沒有定義全局函數(模塊在私有範圍內調用)。


或者,如果你的意思是Controller是一個構造,那麼你需要通過new調用它,並且稍微重新組織:通過new

function Controller() { 
    var self = this; // If you need it for something, you don't in your example 
    self.get = function get() { 
     res.send({ 
      success: 'you got me' 
     }); 
    }; 
} 

module.exports = Controller; 

然後使用它:

var Controller = require('./.Controller.js'); 

var c = new Controller(); 
c.get("foo", "bar"); 

也可能值得指出的是,require('../Controller.js')使用父目錄中的Controller.js文件,而不是當前目錄。以防萬一,這是不是故意的,你得到TypeError: Controller.get is not a function,因爲你得到了錯誤的文件。

+0

感謝您的好解釋。我會嘗試並回應。 – garenyondem

+0

感謝您將我的代碼轉換爲您的第一個建議,並且現在可以使用。 – garenyondem