2017-01-09 97 views
0

我是Node和JS的新手,試圖實現一個模塊。在我的模塊內部我想要一個對象,我可以在我的模塊的其他方法中初始化它的實例(特別是在我的情況下,它是一個響應對象)。 所以我的代碼是:在模塊中創建一個對象及其實例JS,NODE

exports.myModule = { 

//response object 
Response: function() 
{ 
    // some initializing and functions 
    function testFunction(){ 
     console.log("test function inside object was called"); 
    } 
} 



//now i am trying to create an instance 
tester: function() { 
    var res = new Response(); 
    res.testFunction(); 
} 
} 

但是我得到的是我不明白 語法錯誤(這個代碼是沒有意義的它的目的,因爲我還在測試對象的基本建立在我的模塊,

EDITED

現在創建一個新的響應時,我得到的錯誤: 的ReferenceError:未定義響應

+0

讓我們來看看dat error喲! –

+1

主要是因爲我看到的語法問題遍佈片斷您提供^^ –

+0

請參閱編輯@TheDembinski, – Eysiliator

回答

0

嘗試像

var Foo = { 

//response object 
Response: function() 
{ 
    // some initializing and functions 
    function testFunction(){ 
     console.log("test function inside object was called"); 
    } 
} 



//now i am trying to create an instance 
tester: function() { 
    var res = new Foo.Response(); 
    res.testFunction(); 
} 
} 
module.exports = Foo; 

首先 - 這有很大的問題。像Response方法只是奇怪。但我不想編輯你的原始代碼片段。

而且就像我在評論中提到的那樣,即使您修復了明顯的錯誤,我建議您只需在此處使用Google搜索節點教程即可。

編輯:如果有人發現他們在這裏,請參考OP在做一些一般性背景知識工作後提供的答案。

工作示例可能類似於:

module.exports = { 

    //response object 
    Response: function() 
    { 
     // some initializing and functions 
     this.testFunction = function(){ 
      console.log("test function inside object was called"); 
     } 
    }, 


    //now i am trying to create an instance 
    tester: function() { 
     var res = new this.Response(); 
     res.testFunction(); 
    } 
}; 
+0

謝謝,現在我得到的消息:的ReferenceError:美孚沒有定義 我google搜索的是,僅僅明確找不到這種情況下,也許是因爲我不是最好的方式做 – Eysiliator

+0

確保你看看所有的東西!如果您已完成此線程,請繼續並刪除它或接受答案。 –

+0

有一個錯誤;函數testFunction(){'應該是'this。testFunction = function(){' –

1

我最終通過採取這樣的模塊之外的對象聲明解決了這個:

function Response(){ 
// some initializing and functions 
    function testFunction(){ 
     console.log("test function inside object was called"); 
    } 
} 

var Foo = { 

//now i am trying to create an instance 
tester: function() { 
    var res = new Foo.Response(); 
    res.testFunction(); 
    } 
} 
0

的問題是背景。當您執行新的響應時,它會在全局空間中查找它,而該函數未定義。所以,爲了訪問該函數,使用this.Response像我一樣,或者Foo.Response像The Dembinski一樣。

module.exports = { 

    //response object 
    Response: function() 
    { 
     // some initializing and functions 
     this.testFunction = function(){ 
      console.log("test function inside object was called"); 
     } 
    }, 


    //now i am trying to create an instance 
    tester: function() { 
     var res = new this.Response(); 
     res.testFunction(); 
    } 
};