vendredi 18 mai 2018

javascript design patterns Revealing Module Pattern how does that work?

I'm currently learning javascript and design pattern and i read this piece of code that i don't understand. Why, and how, can we access the return object?? I understand that's an invoked function in a function; i understand scope (i think i understand scope, but apparently not).. And here i'm very confuse about why we can acces what's inside the return object and not the rest..

Can you explain that for me please, or give me a link??

(english is not my first language and it's my first question here, so a apologize if i have broke rules)

the code :

// we write the entire object logic as private members and
// expose an anonymous object which maps members we wish to reveal
// to their corresponding public members

var namesCollection = (function() {



 // private members
    var objects = [];

    function addObject(object) {
        objects.push(object);
    }

    function removeObject(object) {
        var index = objects.indexOf(object);
        if (index >= 0) {
            objects.splice(index, 1);
        }
    }

    function getObjects() {
        return JSON.parse(JSON.stringify(objects));
    }

    // public members
    return {
        addName: addObject,
        removeName: removeObject,
        getNames: getObjects
    };
})();

namesCollection.addName("Bob");
namesCollection.addName("Alice");
namesCollection.addName("Franck");
// prints ["Bob", "Alice", "Franck"]
console.log(namesCollection.getNames());
namesCollection.removeName("Alice");
// prints ["Bob", "Franck"]
console.log(namesCollection.getNames());

The source : https://www.toptal.com/javascript/comprehensive-guide-javascript-design-patterns

Aucun commentaire:

Enregistrer un commentaire