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 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.


    jim = function() {
        alert('Hello 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.

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


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

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.