Skyler Skyler - 1 year ago 65
Javascript Question

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 ",...)".

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

), or would this be introducing unneeded complexity?


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() {

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



Answer Source

There is no best practise. Both

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


function privateMethod(message) {
    // do something with `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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download