Function scopes in Javascript

How do I create private methods when building classes in Ext? In this case I’d like to split one method into parts to modularise it, but keep each part private.

It looks as if functions defined within functions live in function scope in Javascript. This can be tested on the console in Chrome. If using the console the below has to be entered as one line. I have formatted it here for clarity.

(function(){
    function fred() {
        alert('Hello'); 
    };

    fred(); 
})();

This results in a “Hello” alert as expected, but after it is run an attempt to call fred() does not work. The function fred was local to the outer function scope.

However:

(function(){
    jim = function() {
        alert('Hello Jim'); 
    };

    jim(); 
})();

This alerts “Hello Jim” as expected, but once it has run a call to jim() also produces the alert. The variable jim was declared without the var keyword so has become global.

(function(){
    var jane = function() {
        alert('Hello Jane'); 
    };

    jane(); 
})();

The function jane() is now private because of the var keyword.

This entry was posted in javascript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.