简体   繁体   中英

Module pattern - separation of concerns - encapsulation in ES6

I am about to rewrite an app (it is in vanilla JS originally) in ES6, in which module patter is apllied.

In no time, at the beginning I realized that I am struggling to get 'separation of concerns' done since if we are about to apply data privacy in ES6 we only use "{}" but not IIFE's as in case of vanilla JS (which as known are practically function expressions).

Vanilla JS solution:

var budgetController = (function() {

    const x = 20;

    function add(a) {
        return x + a;
    }   

    return {
        getSum: function(b){
            console.log(add(b));
        } 
    }
})();



UIController = (function() {

    // some code

})();



Controller = (function(BudgetCrtl, UICtrl) {

    var n = BudgetCrtl.getSum(3);
    console.log(n);

})(budgetController, UIController);

In ES6 I attemted to use simply func expressions not IIFE's in order to pass the other modul in the controller modul and be able to use/pass over the public methods but it dod not work.

ES6 attempt:

let budgetController = function() {
    const x = 20;
    function add(a) {
        return x + a;
    }   
    return {
        getSum: (b) => console.log(add(b))
    }
}



UIController = function() {
    // some code
}



Controller = function(BudgetCrtl, UICtrl) {
    const n = BudgetCrtl.getSum();
    console.log(n);
}
Controller(budgetController, UIController);

Could anyone provide me with some solution to involve somehow in ES6 the so called encapsulation and above mentioned things? Any idea would be appreciated! Cheers, thank you!

You need to execute that BudgetCrtl to get access to the getSum function like so BudgetCrtl().getSum(3) , since that BudgetCrtl is a function and not
a value returned from it's execution .

plus if you want the value to be stored to the n you should not console.log in the arrow function immediately, because the way it is now it's implicitly returning undefined

 let budgetController = function() { const x = 20; function add(a) { return x + a; } return { getSum: (b) => { let newVal = add(b) console.log(newVal) return newVal // so that you can store the value in `n` } } } UIController = function() { // some code } Controller = function(BudgetCrtl, UICtrl) { const n = BudgetCrtl().getSum(3); console.log(n); } Controller(budgetController, UIController); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM