2016-12-26 67 views
-2

module1.js參考對象,模塊出口

module.exports = function (input, input2) { 

    var user = { 

     email: function() { 
      return "exp"; 
     } 

    } 

    return user; 


} 

modulegetter.js

var module1 = require('.../module1.js'); //correct path. 

console.log(module1.user.email()); 

目的:我想引用電子郵件功能的內導出函數內的用戶var,我該怎麼做?

我已經把現在不工作,我運行它,並得到該代碼:

"Cannot read property 'email' of undefined" 

回答

1

這應該是能夠調用email方法:

const module1 = require('module1.js'); 
module1(a, b).email(); 

模塊導出一個構造函數。您必須調用該構造函數,然後當您使用module1(a, b)調用該函數時,您將獲得一個對象,該對象上有一個.email()方法。

你顯然是試圖做:

module1.user.email(); 

這有兩個獨立的東西錯。

  1. 您需要使用module1(a, b)調用構造函數。 module1只是一個在你的實現中沒有屬性的函數。要獲取用戶對象,您必須調用該函數。

  2. 返回對象上沒有.user屬性。調用構造函數的返回值是整個用戶對象,因此您只需在其上直接引用.email()方法即可。

+0

爲什麼我不需要引用'.user',其中包含email()fn? – Marodian

+0

@Marodian - 你顯然有一種誤解,認爲函數內部聲明的局部變量在某種程度上可以作爲函數的屬性訪問,而不執行該函數。這在Javascript中完全不成立。一個局部變量在一個函數之外是不可訪問的,你聲明你的模塊的方式是它所導出的所有函數。要獲得'user'對象,你必須執行那個函數。然後,該函數返回一個具有'.email'屬性的對象。 – jfriend00

0

導出功能爲 '先進' 使用 module.exports系統。想想這樣說:

1.

簡單模塊可導出文本值[易peasy]:

// file1.js 
module.exports = 12; 

// file2.js 
var x = require('file1.js'); 
console.log(x); // 12 

2.

一個模塊那導出函數[在被調用之前什麼也不做]]:

// file3.js 
module.exports = function() { 
    console.log('somebody run me'); 
} 

// file4.js 
var x = require('file3.js'); 
console.log(x); // oops a [function] 
// ... but 
console.log(x()); // yay; somebody run me 

3。

一個模塊該出口被調用的函數[便於終端用戶]:

// file5.js 
module.exports = function() { 
    console.log('somebody run me, now'); 
}(); 

// file5.js 
var x = require('file5.js'); 
console.log(x); // somebody run me, now 

4.

最後,一個模塊一個導出一個可調用功能,在需要的參數[更復雜,但更靈活]:

// file6.js 
module.exports function (foo) { 
    return "foo-" + foo; 
}; 

// file7.js 
var x = require('file6.js'); 
var result = x('something'); 
console.log(result); // foo-something