Alicia Brandon Alicia Brandon - 5 months ago 8
jQuery Question

unexpected token ( using modular pattern

https://jsfiddle.net/4qv24djp/1/

var module_pattern = (function() {
var private = 'private';

a: function() {
console.log('function a and the private variable is ' + private);
},

b: function() {

}

return {
a: a
}
})();

module_pattern.a();


What's wrong with above code? I expect it will print the console of function
a

Answer

You declared the variables with : whereas you need to use a =. The colon is only used within object declarations. You also did not end the line with a ; but with a ,. Variables a and b need a var in front of them. Otherwise, they will be globally accessible and that's exactly what you wouldn't want with the modular pattern.

See the working fiddle: https://jsfiddle.net/4qv24djp/3/

var module_pattern = (function() {
    var private = 'private';

    var a = function() {
      console.log('function a and the private variable is ' + private);
    };

    var b = function() {

    };

    return {
        a: a
    }
})();

module_pattern.a();

You could also directly return the functions in an object:

var module_pattern = (function() {
    var private = 'private';

    return {
        a: function() {
            console.log('function a and the private variable is ' + private);
        },
        b: function() {

        }
    };
})();

module_pattern.a();