proxy 收集

AngDH發表於2024-06-20

window.luan_text = "";
window.luan_open = false;
function luan_proxy(arr, name) {
  // arr 記憶體
  // name 名字

  // 獲取資料型別
  function get_value_type(value) {
    // 'undefined', 'null', 'boolean', 'string', 'number', 'symbol', 'array', 'object', 'function'
    if (Array.isArray(value)) {
      return "array";
    }
    if (value == null) {
      return "null";
    }
    return typeof value;
  }
  // 列印函式
  function luan_print(obj) {
    let type = get_value_type(obj);
    if (["undefined", "null", "boolean", "string", "number"].includes(type)) {
      return obj;
    } else if (obj[Symbol.toStringTag]) {
      return obj[Symbol.toStringTag];
    } else if (type == "function") {
      return `function ${obj.name}`;
    } else if (type == "object" || type == "array") {
      // JSON.stringify 會遞迴處理
      let temp = JSON.stringify(obj, function (k, v) {
        if (v && v[Symbol.toStringTag]) {
          return v[Symbol.toStringTag];
        } else if (v && typeof v == "function") {
          return `function ${v.name}`;
        } else {
          return v;
        }
      });
      return temp;
    } else if (type == "symbol") {
      return obj.toString();
    } else {
      // 未預料到的情況
      debugger;
    }
  }

  // 控制代碼
  let handle = {
    get(target, property, receiver) {
      let result;
      result = Reflect.get(target, property, receiver);
      try {
        if (window.luan_open) {
          let content = luan_print(target);
          window.luan_text += `${name}|get| 下標: ${property.toString()} 內容: ${content}\r\n`;
        }
      } catch (e) {
        debugger;
      }
      return result;
    },
    set(target, property, value, receiver) {
      let result;
      result = Reflect.set(target, property, value, receiver);
      try {
        if (window.luan_open) {
          let content = luan_print(target);
          window.luan_text += `${name}|set| 下標: ${property.toString()} 內容: ${content}\r\n`;
        }
      } catch (e) {
        debugger;
      }
      return result;
    },
  };
  return new Proxy(arr, handle);
} //………………
p = luan_proxy(p, "p1");

相關文章