How best to implement out params in JavaScript?

后端 未结 9 1613
盖世英雄少女心
盖世英雄少女心 2020-12-15 03:36

I\'m using Javascript with jQuery. I\'d like to implement out params. In C#, it would look something like this:

/*
 * odp      the object to test
 * error            


        
9条回答
  •  余生分开走
    2020-12-15 04:12

    I am using a callback method (similar to Felix Kling's approach) to simulate the behavior of out parameters. My answer differs from Kling's in that the callback function acts as a reference-capturing closure rather than a handler.

    This approach suffers from JavaScript's verbose anonymous function syntax, but closely reproduces out parameter semantics from other languages.

    function isLegal(odp, out_error) {
        //...
        out_error("ODP failed test foo"); // Assign to out parameter.
        return false;
    }
    
    var error;
    var success = isLegal(null, function (e) { error = e; });
    
    // Invariant: error === "ODP failed test foo".
    

提交回复
热议问题