Three features of JS and functional languages

  • 2020-03-30 02:17:20
  • OfStack

Save data in a function
In imperative languages, private variables (local variables) inside functions cannot be saved. In terms of the execution of the program, local variables are allocated on the stack, and the occupied stack is released after the execution of the function. Therefore, the data in the function cannot be saved.
In JavaScript functions, private variables in a function can be modified, and the modified state persists when the function is "entered" again. The following example illustrates this feature:


  var set,get;
  function MyFunc(){
      var value = 100;
      function set_value(v){
          value = v;
      }
      function get_value(){
          return value;
      }
      set = set_value;
      get = get_value;
  }  
  MyFunc();
  console.log(get()); //100
  set(300);
  console.log(get()); //300

An obvious benefit is that if a data can be persisted in a function, then the function (as a constructor) can be assigned to an instance using the data to perform an operation. In multiple instances, the data is in different closures, so it doesn't affect each other.
In object-oriented terms, this means that different instances have their own private data (copied from some public data). The following example illustrates this feature:

  function MyObject(){
      var value = 100;
      this.setValue = function(){
          value = v;
      }
      this.showValue = function(){
          console.log(value);
      }
  }
  var obj1 = new MyObject();
  var obj2 = new MyObject();
  obj2.setValue(300);
  obj1.showValue(); //100;

Third, the operation inside the function has no side effect outside the function
The meaning of this feature is:
* functions operate with an entry parameter without modifying it (as a value parameter rather than a variable parameter)
* does not modify the value of other data outside the function during the operation (such as global variables)
* pass the value to the external system through "function return" after operation

Such functions have no side effects on external systems during operation. However, we notice that JavaScript allows global variables to be referenced and modified within functions, and even to be declared. This is actually breaking its functional nature.
In addition, JavaScript also allows you to modify objects and group members within functions -- members that should be modified by object methods rather than by other functions outside the object system.
So: JavaScript is a feature that can only be guaranteed by the programming habits of developers.


Related articles: