24/33 What is the purpose of having a function inside a function?


#1

I solved the instructions, yet I'm utterly confused. Why did we create two functions inside another one instead of writing the second and the third functions outside? Here's the code:

function Rectangle(height, width) {
  this.height = height;
  this.width = width;
  this.calcArea = function() {
      return this.height * this.width;
  };
  this.calcPerimeter = function() {
    return 2*this.height + 2*this.width
  };
  
}

var rex = new Rectangle(7,3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();

Can't we just put it this way for the other functions:

function calcPerimeter = function() {
      this.height = height;
      this.width = width;
     return 2*this.height + 2*this.width
};

#2

In technical terms, a function in a function is known as a closure.

function foo(a) {
    return function(b) {
        return a * b;
    };
}
m5 = foo(5);
console.log(m5(10));   // 50
m7 = foo(7);
console.log(m7(5));    // 35

The inner function is returned as a callable that retains the variable a in parent function scope. m5() and m7() are those functions. When we call them with a single parameter, it is passed to the inner function and multiplied by the outer scoped value.

Methods work on the same prinicipal. The declared variables of the new object are in parent function scope with the execution context, this which is the new object. The parent function cannot see inside the method, but the method can see this and all its associated properties, such as this.height and this.width.

When we instantiate a new object, its methods are closures with the constructor variables retained in outer scope.

I'm terrible at explaining this so a little reading on closures will go a long way to sort things out. This should give you something to go on, though.


#3

function foo(a) {
    return function(b) {
        return a * b;
    };
}

How many times do we multiply by PI or E? How many fundamental functions boil down to mutiplication? The idea here is that we can introduce a constant into a function, and closures let us do this in a dynamic way. We can have unlimited instances of a closure, making it fundamental to the backbone of object oriented JS. A closure is a stateful function that retains its parent scope. It is ideally suited to this purpose.

var mPI = foo(Math.PI);
var mE = foo(Math.E);
 > mPI(2)
=> 6.283185307179586
 > mE(Math.PI)
=> 8.539734222673566
 > mE(mPI(1))
=> 8.539734222673566

#4

In conclusion, we know that functions give closure to the local variables. They cannot be seen from the outside. Closures are very much the same, except they are functions, not variables. It takes a minute to wrap our head around. Especially given that they still exist after the called function has been exited.