Is Javascript a Functional Programming Language?

前端 未结 13 854
天涯浪人
天涯浪人 2020-12-04 05:22

Just because functions are first class objects, there are closures, and higher order functions, does Javascript deserve to be called a Functional Programming language? The

13条回答
  •  温柔的废话
    2020-12-04 05:44

    What I really hate in javascript (if You try to look at it as FP language) is this:

    function getTenFunctionsBad() {
      var result = [];
      for (var i = 0; i < 10; ++i) {
        result.push(function () {
          return i;
        });
      }
      return result;
    }
    
    function getTenFunctions() {
      var result = [];
      for (var i = 0; i < 10; ++i) {
        result.push((function (i) {
          return function () {
            return i;
          }
        })(i));
      }
      return result;
    }
    
    var functionsBad = getTenFunctionsBad();
    var functions = getTenFunctions()
    for (var i = 0; i < 10; ++i) {
      // using rhino print
      print(functionsBad[i]() + ', ' + functions[i]());
    }
    
    // Output:
    //   10, 0
    //   10, 1
    //   10, 2
    //   10, 3
    //   10, 4
    //   10, 5
    //   10, 6
    //   10, 7
    //   10, 8
    //   10, 9
    

    You need to understand JS stack environment (I don't if it is the right term) to understand such a behavior.

    In scheme for example You just can't produce such thing (Ok, ok -- with the help of underlying languages' references You can make it):

    (define (make-ten-functions)
      (define (iter i)
        (cond ((> i 9) '())
              (else (cons (lambda () i) (iter (+ i 1))))))
      (iter 0))
    
    (for-each (lambda (f)
                (display (f))
                (newline)) (make-ten-functions))
    

提交回复
热议问题