Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Last active February 6, 2018 13:00
Show Gist options
  • Save Ugarz/9eb0d8e28016b2ff1e44a6fd8bff9c17 to your computer and use it in GitHub Desktop.
Save Ugarz/9eb0d8e28016b2ff1e44a6fd8bff9c17 to your computer and use it in GitHub Desktop.
Reflexion around Prototype pattern in Javascript

Prototypal pattern

Let's say I want a provider to request a file

// Create the Provider
const Provider = function(datas) {
    if(!datas || !datas.provider) console.warn('Nope, need a provider')
    const { provider } = datas;
    this.provider = provider;
}

// Attach a function to the Provider
Provider.prototype.requestFile = function(informations) {
    if (informations) {
        console.log(`Le provider est ${this.provider}`);
        return console.log(`Bonjour, je demande le fichier avec ${JSON.stringify(informations)}`);
    }
    return console.warn('Need informations to request the file');
}

// Instanciate the Provider
const P = new Provider({ provider: 'google'})
const M = new Provider({ provider: 'duckduckgo'})

// Use the Provider's requests
P.requestFile({ name: "toto" })
M.requestFile({ name: "toto" })

module.exports = Provider;

More here : https://youtu.be/hS_WqkyUah8?t=7m41s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment