2017-06-12 53 views
1

我想達到以下設置:訪問閉包內的功能,從導入模塊

// app.js 
(function() { 
    const add = function() { 
     // add 
    } 
    const substract = function() { 
     // substract 
    } 

    require('./module1'); 
    require('./module2'); 
})() 


// module1.js 
add(); 
substract(); 

的問題是,當功能從module1.js中調用,他們是不確定的(這一切都是捆綁webpack)。

我知道各種模塊/文件之間「導出」和「導入」的解決方案。我只是想知道我是否可以實現這一設置,以避免導入我使用的許多模塊(想象一下,例如,必須將它們導入到50個模塊/文件中)。

什麼是實現此設置的正確方法(如果可能)?

Thanx提前。如果你能

+0

你需要擔心的唯一的事情是你需要模塊1,並將2.如果它們被正確導入路徑,一切都將工作得很好 – binariedMe

+1

如果你想在1單元使用這些功能,你不應該是這樣做反過來呢? – Niels

+1

@binariedMe不,它不會工作。變量'add'和'subtract'只能在閉包的_lexical_範圍內使用,並且不會暴露給其中任何需要的模塊。 – Alnitak

回答

0

試試這個:

// app.js

(function addSubst() { 
    const add = function() { 
     // add 
    } 
    const substract = function() { 
     // substract 
    } 

    require('./module1'); 
    require('./module2'); 
})() 

// module1.js

import {addSubst} from 'app';//app.js 
add(); 
substract(); 

better explanation and for more languajes here

0

的IIFE函數結束的範圍之後它稱之爲自我和內部addsubstract ,他們將不會在IIFE之後提到你應該嘗試從這個文件中導出兩個變量。如果你嘗試應用clousure

function currentModule() { 
    const add = function() { 
     // add 
    } 
    const substract = function() { 
     // substract 
    } 
return { add : add, substract : substract} 
}) 
var instanceHere = currentModule(); 
instanceHere.Add(); 
0

我設法做到這一點的方法是爲我的應用程序創建一個全局對象(命名空間)。

(function() { 
    APP = window.APP || {}; 

    APP.add = function() { 
     console.log('Adding...'); 
    } 
    APP.substract = function() { 
     console.log('Substracting...'); 
    } 

    // Import the modules. 
    require('./module1'); 
    require('./module2'); 
})(); 

// module1.js 
APP.add();  // Outputs "Adding..." 
APP.substract(); // Outputs "Substracting..."