locked
javascript module pattern RRS feed

  • Question

  • User1183902823 posted

    tell me how could i call public and private method of a SearchEngine module from out side....need a example. thanks

    var SearchEngine = (function ( ) { 
        //Private Method.
        var luckyAlgo = function ( ){
            //create one random number.
            return Math.floor(Math.random()*11);
        }
        //Returning the object
        return {
            //privileged method.
            getYourLuckyNumber : function ( ){
                //Has access to its private method because of closure.
                return luckyAlgo();        
            }
        } 
    } ) ( );

    Friday, November 24, 2017 12:31 PM

Answers

  • User475983607 posted

    tell me how could i call public and private method of a SearchEngine module from out side....need a example. thanks

    By definition private functions are not visible to the outside. 

    Implementation:

    SearchEngine.getYourLuckyNumber()

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 24, 2017 12:39 PM

All replies

  • User475983607 posted

    tell me how could i call public and private method of a SearchEngine module from out side....need a example. thanks

    By definition private functions are not visible to the outside. 

    Implementation:

    SearchEngine.getYourLuckyNumber()

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 24, 2017 12:39 PM
  • User753101303 posted

    Hi,

    Or if you prefer you don't have private and public keywords in JavaScript. So it is basically emulated here by :
    - declaring a local object with a method. As the object is local it can be called only from with the parent object (which is a function, in js everything is an object including functions)
    - returning an object that happens to have a function so it can be called by any code that gets this returned object

    Friday, November 24, 2017 1:02 PM