console.log 输出当前所在函数名edit icon

作者:
lynn-ssk
Fork(复制)
下载
嵌入
BUG反馈
index.html
md
README.md
现在支持上传本地图片了!
index.html
            
            <!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      .title {
        margin-top: 95px;
        text-align: center;
      }
      .desc {
        color: #777;
        text-align: center;
      }
    </style>
  </head>

  <body>
    <h1 class="title">
      Hello 笔.COOL
    </h1>

    <p class="desc">
      <i>一笔一划,绘就人生;一码一境,酷创未来。</i>
    </p>

    <img
      src="https://bi.cool/static/case-materials/icons/html.svg"
      style="width: 48px; height: 48px; display: block; margin: 30px auto"
    />

    <script>
      function getFunctionName() {
  // 创建一个 Error 对象并获取堆栈
  const stack = new Error().stack;
        console.log(stack)
  if (!stack) return 'anonymous';

  // 按换行符分割堆栈信息
  const lines = stack.split('\n');
  
  // 寻找调用 getFunctionName 的那一行
  // 索引说明:
  // 0: "Error"
  // 1: "at getFunctionName ..." (当前函数自身)
  // 2: "at doSomething ..." (调用者,也就是我们想要的函数名)
  const targetLine = lines[2]; 

  if (!targetLine) return 'anonymous';

  // 使用正则提取 "at 函数名 " 或 "at Object.方法名 "
  // 匹配规则:at 后面跟着空格,然后捕获非空格字符,直到遇到空格、左括号或结尾
  const match = targetLine.match(/^\s+at\s+(?:(.*?)\s+\()?(?:(.*?):\d+:\d+)?\)?$/);
  
  if (match && match[1]) {
    // match[1] 可能是 "Object.myMethod" 或 "myFunction",处理一下去掉 "Object."
    let name = match[1].replace(/^Object\./, '');
    // 如果提取出来的是类似 "new MyConstructor" 这样的,可以按需处理
    if (name.startsWith('new ')) name = name.substring(4);
    return name;
  }

  return 'anonymous';
}

// === 测试 ===
function doSomething() {
  console.log(`当前函数名: ${getFunctionName()}`);
}

const obj = {
  myMethod() {
    console.log(`当前函数名: ${getFunctionName()}`);
  }
};

doSomething();       // 输出: 当前函数名: doSomething
obj.myMethod();      // 输出: 当前函数名: myMethod
    </script>
  </body>
</html>

        
编辑器加载中
预览
控制台