javascriptscopeprivaterevealing-module-pattern

Best Practices for accessing private methods in the revealing module pattern


Almost every revealing module pattern tutorial that I've seen will show a public method access a private method without using "method.call(this,...)".

This seems to get the job done alright, but if you do a trace(this) in the private method, it will show "Window". This feels like a potential gotcha.

Should I be using call (or apply), or would this be introducing unneeded complexity?

plunk: https://plnkr.co/edit/hc3ZPJyeHcT9bLbLaLpX?p=preview

EDIT: My thinking is that by using "call", it somehow makes it "safer" since the context is the api object rather than the global namespace.

var Module = (function () {

    var _privateVar = "PRIVATE!";

    var api = {
        publicMethod: publicMethod
    }

    return api;

    function publicMethod() {
        privateMethod();
        privateMethod.call(this);
    };

    function privateMethod(message) {
        console.log(_privateVar, this);
    };


})();

Module.publicMethod();

Solution

  • There is no best practise. Both

    function privateFunction(self, message) { // also popular: `that`
        // do something with `self`
    }
    …
    privateFunction(this, …);
    

    and

    function privateMethod(message) {
        // do something with `this`
    }
    …
    privateMethod.call(this, …);
    

    are fine. Just stick to one style and keep your code base consistent. However, the first one might be more popular because many private functions are actually static and don't need an instance to work with, so it simplifies things to use explicit parameters for the instance (instead of assuming/hoping that the function is called with the expected this value).