使用回调的变量范围 - JavaScript

时间:2017-11-21 07:10:10

标签: javascript promise

在下面的代码中,

   /**
     * Generate a random uuid of the specified length. Example: uuid(15) returns
     * "VcydxgltxrVZSTV"
     *
     * @param len the desired number of characters
     * @return 
     */
    public static String uuid(int len) {
        return uuid(len, CHARS.length);
    }

    /**
     * Generate a random uuid of the specified length, and radix. Examples: <ul>
     * <li>uuid(8, 2) returns "01001010" (8 character ID, base=2) <li>uuid(8,
     * 10) returns "47473046" (8 character ID, base=10) <li>uuid(8, 16) returns
     * "098F4D35" (8 character ID, base=16) </ul>
     *
     * @param len the desired number of characters
     * @param radix the number of allowable values for each character (must be
     * <= 62)
     * @return 
     */
    public static String uuid(int len, int radix) {
        if (radix > CHARS.length) {
            throw new IllegalArgumentException();
        }
        char[] uuid = new char[len];
        // Compact form
        for (int i = 0; i < len; i++) {
            uuid[i] = CHARS[(int) (Math.random() * radix)];
        }
        return new String(uuid);
    }

如果没有匿名回调,window.onload = function(){ function cb(resolve, reject){ var http = new XMLHttpRequest(); http.open(url); http.onload = 1; http.onerror = 2; //http.send(); } function get(url){ return new Promise(cb); } }; 中如何显示名称url

1 个答案:

答案 0 :(得分:3)

它不可见,因为它是在函数get中定义的。您无法在该范围之外访问它。

我可以提出一个解决方案。致电cb并传递url。此cb函数将返回具有实际cb逻辑的函数,并且可以访问url参数。感谢closure

window.onload = function() {

  function cb(url){
    return function(resolve, reject) {
       var http = new XMLHttpRequest();
       http.open(url);
       http.onload = 1;
       http.onerror = 2;
       //http.send();
    };    
  }

  function get(url){
    return new Promise(cb(url));
  }

};