A function inside a JavaScript function without declaring it again each time

can declare a function inside a function in javascript. How:

function my(){
   function check(){
      return true;
   }

   console.log( check() ? "yes" : "no");
}

my();

However, this may not be the fastest, because every time I get called, the check must be re-announced. But an ad check outside my facility could pollute the global area.

If mine was a My constructor , validation can be added to its prototype, but, unfortunately, this does not work with normal functions.

What is a convenient way to solve this problem?

+4
source share
2 answers

check my, my check my :

var my = function() { // <=== Scoping function

    function my(){
        console.log( check() ? "yes" : "no");
    }

    function check(){
        return true;
    }

    return my;        // <=== Returns `my`
}();                  // <=== () calls scoping immediately

my();

check , , my.

. "" , . , .

, parens , , ( , ), , " d ( - ), , , :

var my = (function() { // <=== Scoping function

    function my(){
        console.log( check() ? "yes" : "no");
    }

    function check(){
        return true;
    }

    return my;         // <=== Returns `my`
})();                  // <=== () calls scoping immediately

my();
+9

, , , , - :

function my(){
    // Function code here
    return {
        check : function(){
            return true;
        }
    };
}

var myVar = my();
console.log(myVar.check() ? "true" : "false");
-1

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


All Articles