Question

I'd like to avoid having to remember two names for a method, one for public and one for private access. In that sense, in which case would a script fail if you use same name for both? When would following code fail?

var TestClass = function() {
    function showMessage(text) {
        $("div").text(text);
    }
    return {
        showMessage: showMessage
    };
}();

I've tried it in this fiddle, and it works properly in FF, IE, Chrome, Safari. JSLint has nothing to say about it either.

I've regularly see people naming private method _showMessage or showMessageFn. Is there a good reason for this?

Answer I'm looking for is that it either fails in some situations, may create confusion, or that it's just JavaScript people inventing conventions to seem smart.

Was it helpful?

Solution

This works fine - you're defining a function called showMessage() in the context of your inner function, then assigning it to the showMessage property of your exported object literal.

A property name can be any valid identifier, so showMessage is of course perfectly valid. In your example, function showMessage(text) creates an identifier called showMessage in the inner scope, referencing a function definition. You then create a separate identifier called showMessage as a property name on the object literal, which is assigned the value of the function referenced by the the inner identifier. The fact that both identifiers have the same name is irrelevant as they do not exist in the same scope.

Only problem I can see is that you should wrap the function invocation in parens, otherwise it is not immediately clear to the reader that the function is self-invoking.

So this:

var TestClass = function() {
    ...
}();

Becomes this:

var TestClass = (function() {
    ...
}());

The reason private methods are often prefixed with an underscore is simply a widely used convention - it shows that the method is intended to be private (Javascript doesn't support access modifiers, so any property or method that isn't encapsulated in a closure can be accessed from an outer scope). The accepted answer to this StackOverflow quesion sums it up perfectly.

OTHER TIPS

What you are doing here is returning an object that contains the object of the function you defined.

I think that basically it's a way to show whether you are accessing the function in the same scope that it was created or in a different scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top