Javascript FAB framework on Node.js

前端 未结 2 1613
北恋
北恋 2020-12-15 05:54

I\'ve seen a slide that presented Fab, a node.js framework.

\"Fab

Is this JavaScript?

C

相关标签:
2条回答
  • 2020-12-15 06:28

    Is plain JavaScript, it is a function chaining pattern.

    The first line, ( fab = require("fab") ) includes the fab function and returns a reference to it.

    All the subsequent parentheses are function calls, each function invocation returns probably the same function again and again.

    The pattern probably looks like this simplified example:

    var foo = function (arg) {
      // detect what the argument is
      if (typeof arg == 'function') {
        // do something with arg
        console.log('function: '+arg());
      } else if (arg instanceof RegExp) {
        // arg is a RegExp...
        console.log('A RegExp: '+arg);
      } else if (typeof arg == "string") {
        // arg is a string
        console.log('A string: '+arg);
      }
      return foo; // return a reference to itself
    };
    
    (foo)
      (function() { return "Foo "; })
      (/bar/)
      (" baz!");
    

    Outputs:

    function: Foo
    A RegExp: /bar/
    A string: baz!
    
    0 讨论(0)
  • 2020-12-15 06:28

    That's hard to follow indeed; it doesn't really look like Javascript at all...

    Anyway, FAB takes advantage of returning a pointer to the function which was called. For example:

    function doSomething(str){
      alert(str);
      return arguments.callee;
    }
    
    // Alerts 'hi' and then 'there'
    doSomething('hi')('there');
    

    Of course you can implement extra conditions, like counting the number of arguments or checking the type of arguments passed in. For example:

    function doSomething(){
      if(arguments.length == 1){
        alert(arguments[0])
      } 
      else if(arguments.length == 2){
        alert(arguments[0] + arguments[1]);
      }
    
      return arguments.callee;
    }
    
    doSomething
      ("Hi, 3 + 4 is:")
      (3, 4);
    

    The last example alerts:

    > Hi, 3 + 4 is:
    > 7
    
    0 讨论(0)
提交回复
热议问题