Programing

함수를 반환하는 함수

lottogame 2020. 8. 26. 08:20
반응형

함수를 반환하는 함수


나는 '함수를 반환하는 함수'라는 개념을 고수하고 있습니다. 저는 Stoyan Stefanov의 'Object Oriented Javascript'라는 책을 참조하고 있습니다.

스 니펫 1 :

    function a() {
      
        alert('A!');
    
        function b(){
            alert('B!'); 
        }
    
        return b();
    }
    
    var s = a();
    alert('break');
    s();

산출:

A!
B!
break

스 니펫 2

function a() {
  
    alert('A!');

    function b(){
        alert('B!'); 
    }

    return b;
}

var s = a();
alert('break');
s();
산출:

A!
break
B!

누군가 가 위의 스 니펫에서 반환 b차이를 말해 줄 수 있습니까 b()?


함수에 변수를 할당하면 (괄호없이) 함수에 대한 참조가 복사됩니다. 함수 이름 끝에 괄호를 넣고 함수를 호출하여 함수 반환 값을 반환합니다.

데모

function a() {
    alert('A');
}
//alerts 'A', returns undefined

function b() {
    alert('B');
    return a;
}
//alerts 'B', returns function a

function c() {
    alert('C');
    return a();
}
//alerts 'C', alerts 'A', returns undefined

alert("Function 'a' returns " + a());
alert("Function 'b' returns " + b());
alert("Function 'c' returns " + c());

귀하의 예에서는 함수 내에서 함수를 정의하고 있습니다. 예 :

function d() {
    function e() {
        alert('E');
    }
    return e;
}
d()();
//alerts 'E'

이 함수는 여전히 호출 가능합니다. 여전히 존재합니다. 이것은 JavaScript에서 항상 사용됩니다. 기능은 주위에 전달 될 수있는 단지 다른 값처럼. 다음을 고려하세요:

function counter() {
    var count = 0;
    return function() {
        alert(count++);
    }
}
var count = counter();
count();
count();
count();

The function count can keep the variables that were defined outside of it. This is called a closure. It's also used a lot in JavaScript.


Returning the function name without () returns a reference to the function, which can be assigned as you've done with var s = a(). s now contains a reference to the function b(), and calling s() is functionally equivalent to calling b().

// Return a reference to the function b().
// In your example, the reference is assigned to var s
return b;

Calling the function with () in a return statement executes the function, and returns whatever value was returned by the function. It is similar to calling var x = b();, but instead of assigning the return value of b() you are returning it from the calling function a(). If the function b() itself does not return a value, the call returns undefined after whatever other work is done by b().

// Execute function b() and return its value
return b();
// If b() has no return value, this is equivalent to calling b(), followed by
// return undefined;

return b(); calls the function b(), and returns its result.

return b; returns a reference to the function b, which you can store in a variable to call later.


Returning b is returning a function object. In Javascript, functions are just objects, like any other object. If you find that not helpful, just replace the word "object" with "thing". You can return any object from a function. You can return a true/false value. An integer (1,2,3,4...). You can return a string. You can return a complex object with multiple properties. And you can return a function. a function is just a thing.

In your case, returning b returns the thing, the thing is a callable function. Returning b() returns the value returned by the callable function.

Consider this code:

function b() {
   return 42;
}

Using the above definition, return b(); returns the value 42. On the other hand return b; returns a function, that itself returns the value of 42. They are two different things.


When you return b, it is just a reference to function b, but not being executed at this time.

When you return b(), you're executing the function and returning its value.

Try alerting typeof(s) in your examples. Snippet b will give you 'function'. What will snippet a give you?


Imagine the function as a type, like an int. You can return ints in a function. You can return functions too, they are object of type "function".

Now the syntax problem: because functions returns values, how can you return a function and not it's returning value?

by omitting brackets! Because without brackets, the function won't be executed! So:

return b;

Will return the "function" (imagine it like if you are returning a number), while:

return b();

First executes the function then return the value obtained by executing it, it's a big difference!


Create a variable:

var thing1 = undefined;

Declare a Function:

function something1 () {
    return "Hi there, I'm number 1!";
}

Alert the value of thing1 (our first variable):

alert(thing1); // Outputs: "undefined".

Now, if we wanted thing1 to be a reference to the function something1, meaning it would be the same thing as our created function, we would do:

thing1 = something1;

However, if we wanted the return value of the function then we must assign it the return value of the executed function. You execute the function by using parenthesis:

thing1 = something1(); // Value of thing1: "Hi there, I'm number 1!" 

This is super useful in real life.

Working with Express.js

So your regular express route looks like this:

function itWorksHandler( req, res, next ) {
  res.send("It works!");
}

router.get("/check/works", itWorksHandler );

But what if you need to add some wrapper, error handler or smth?

Then you invoke your function off a wrapper.

function loggingWrapper( req, res, next, yourFunction ) {
  try {
    yourFunction( req, res );
  } catch ( err ) {
    console.error( err );
    next( err );
  }
}

router.get("/check/works", function( req, res, next ) {
  loggingWrapper( req, res, next, itWorksHandler );
});

Looks complicated? Well, how about this:

function function loggingWrapper( yourFunction ) => ( req, res, next ) {
  try {
    yourFunction( req, res, next );
  } catch ( err ) {
    console.error( err );
    next( err );
  }
}

router.get("/check/works", loggingWrapper( itWorksHandler ) );

See at the end you're passing a function loggingWrapper having one argument as another function itWorksHandler, and your loggingWrapper returns a new function which takes req, res, next as arguments.

참고URL : https://stackoverflow.com/questions/7629891/functions-that-return-a-function

반응형