What type of template / object is in Javascript?

I see this template a lot (which I really use), but I want to explain how it works.

var mystuff = function() {


    var blah = function() {

    };


    return {

        setup: function() {
              blah();
        };

    };


}();

Then use is very similar to OOP:

mystuff.setup();
+3
source share
6 answers

What it does is returning a public interface to your object. It looks like you are using a public function setup()to access a private function blah(). This is one way to emulate public and private member functions in Javascript objects.

Since it is mystuffdefined with this final ()bottom, it is executed immediately when the parser reaches mystuff.setup()and actually returns an anonymous object (your public interface) using the method setup().

+6

, . .

"Module pattern" ( Crockford , blogged ).

:

  • ( "function")
  • "" (vars, functions ..), ( return)
  • "", , , ( return)

.

+6

JavaScript. "OOP-" , .

, , . JavaScript , " ", . , .

+2

- . () () , , , . , , , . - , closure.

.

0

, .

.

function() { .... } .
function() { .... }() .

- , JSON ( Javscript)

{ setup : .... } - : setup, .

mystuff , (), setup, mystuff.setup() setup.

, , , setup blah, , .

, closure (. ) ( . wikipedia)

, .

crescentfresh answer

0

, , :

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

, -, . :\

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

, . " " JavaScript. - , , , .

Encapsulation simply means that you make some members private. What is private in this case? Well, the blah variable is private in this case . Please learn how to start participating in private individuals, emphasizing that they are private. Good coding practice distinguishes public methods from private methods with underscores.

<script type="text/javascript">
var obj=(function(){
    //private members
    var _p={};//toss all private members into a single object.
    _p.list=[];
    _p.init=function(){
        _p.list=[];
    };

    //public members. use "this" to reference object followed by the method.
    //however obj._p.list won't be accessible to the global scope
    return {
        reset:function()
         {
            _p.init();
         }
        ,addName:function(str)
         {
            _p.list.push(''+str);//limit to strings
         }
         ,getNames:function()
          {
            return _p.list.slice(0);//return a clone
          }
         ,alertNames:function()
          {
            alert(this.getNames().join(","));
          }
         ,getPrivateObj:function()
          {
            return _p;
          }
    };
})();

obj.alertNames();
obj.addName("Nandan");
obj.addName("Ram");
obj.alertNames();
obj.reset();
obj.alertNames();
obj.addName("Vinoth");
obj.addName("Kevin");
obj.alertNames();
alert(typeof obj._p);//undefined
var privateObj=obj.getPrivateObj();
alert(typeof privateObj);
alert(privateObj.list.join("|"));
</script>
0
source

Source: https://habr.com/ru/post/1721558/


All Articles