복붙노트

[JQUERY] 나는 자바 스크립트에서 현재 실행중인 함수의 이름을받을 수 있나요?

JQUERY

나는 자바 스크립트에서 현재 실행중인 함수의 이름을받을 수 있나요?

해결법


  1. 1.ES5 이상에서는 해당 정보에 대한 접근이 없습니다.

    ES5 이상에서는 해당 정보에 대한 접근이 없습니다.

    JS의 이전 버전에서는 arguments.callee를 사용하여 그것을 얻을 수 있습니다.

    아마 몇 가지 추가 정크 포함됩니다대로, 이름 불구을 구문 분석 할 수 있습니다. 비록, 일부 구현에 당신은 단순히 arguments.callee.name를 사용하여 이름을 얻을 수 있습니다.

    구문 분석 :

    function DisplayMyName() 
    {
       var myName = arguments.callee.toString();
       myName = myName.substr('function '.length);
       myName = myName.substr(0, myName.indexOf('('));
    
       alert(myName);
    }
    

  2. 2.익명이 아닌 함수의 경우

    익명이 아닌 함수의 경우

    function foo()
    { 
        alert(arguments.callee.name)
    }
    

    그러나 오류 처리기의 경우에 결과는 않을 것, 에러 핸들러 함수의 이름이됩니다?


  3. 3.당신이 필요한 모두는 간단하다. 함수를 만듭니다 :

    당신이 필요한 모두는 간단하다. 함수를 만듭니다 :

    function getFuncName() {
       return getFuncName.caller.name
    }
    

    당신이 필요로 할 때마다, 당신은 단순히 사용하는 것이 후 :

    function foo() { 
      console.log(getFuncName())
    }
    
    foo() 
    // Logs: "foo"
    

  4. 4.MDN에 따르면

    MDN에 따르면

    언급 한 바와 같이이 스크립트는 "엄격 모드"를 사용하는 경우에만 적용됩니다. 이 보안상의 이유로 주로 슬프게 현재 이에 대한 대안이 없습니다.


  5. 5.이것은을 수행해야합니다

    이것은을 수행해야합니다

    var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
    alert(fn[1]);
    

    호출자의 경우, 단지 caller.toString ()를 사용합니다.


  6. 6.이는 "세계에서 가장 추한 해킹"의 범주에 가야하지만 여기 당신은 간다.

    이는 "세계에서 가장 추한 해킹"의 범주에 가야하지만 여기 당신은 간다.

    첫번째로는, (다른 답변에서와 같이) 현재 함수의 이름을 인쇄하면 이후, 나에게 제한적으로 사용이 가지 이미 기능이 무엇인지 모르는 것 같다!

    그러나, 호출하는 함수의 이름에서 찾는 것은 추적 기능에 매우 유용 할 수 있습니다. 이것은 정규 표현식으로하지만, 사용 같이 IndexOf 빠른 배에 관한 것이다 :

    function getFunctionName() {
        var re = /function (.*?)\(/
        var s = getFunctionName.caller.toString();
        var m = re.exec( s )
        return m[1];
    }
    
    function me() {
        console.log( getFunctionName() );
    }
    
    me();
    

  7. 7.여기에 작동하는 방법이있다 :

    여기에 작동하는 방법이있다 :

    export function getFunctionCallerName (){
      // gets the text between whitespace for second part of stacktrace
      return (new Error()).stack.match(/at (\S+)/g)[1].slice(3);
    }
    

    그런 다음 테스트에서 :

    import { expect } from 'chai';
    import { getFunctionCallerName } from '../../../lib/util/functions';
    
    describe('Testing caller name', () => {
    
        it('should return the name of the function', () => {
          function getThisName(){
            return getFunctionCallerName();
          }
    
          const functionName = getThisName();
    
          expect(functionName).to.equal('getThisName');
        });
    
      it('should work with an anonymous function', () => {
    
    
        const anonymousFn = function (){
          return getFunctionCallerName();
        };
    
        const functionName = anonymousFn();
    
        expect(functionName).to.equal('anonymousFn');
      });
    
      it('should work with an anonymous function', () => {
        const fnName = (function (){
          return getFunctionCallerName();
        })();
    
        expect(/\/util\/functions\.js/.test(fnName)).to.eql(true);
      });
    
    });
    

    테스트가 / 폴더의 유틸리티 / 기능에있는 경우 세 번째 시험에만 동작합니다


  8. 8.반환 아래의 스 니펫 호출하는 함수의 이름에 getMyName 기능. 그것은 해킹 및 비 - 표준 기능에 의존 : Error.prototype.stack. 이 아마 모든 곳에서 작동하지 않도록 Error.prototype.stack에 의해 반환 된 문자열의 형식이 서로 다른 엔진에서 다르게 구현되어 있습니다 :

    반환 아래의 스 니펫 호출하는 함수의 이름에 getMyName 기능. 그것은 해킹 및 비 - 표준 기능에 의존 : Error.prototype.stack. 이 아마 모든 곳에서 작동하지 않도록 Error.prototype.stack에 의해 반환 된 문자열의 형식이 서로 다른 엔진에서 다르게 구현되어 있습니다 :

    getMyName 함수 () { VAR 전자는 새로운 오류 ( '더미') =; VAR 스택 = e.stack .split ( "\ n") [2] // => "FUNCTIONNAME" "FUNCTIONNAME (...에서" .replace (\ S + (AT / ^ \ S + +) \ S + / g, '$ 1'.?.); 리턴 스택 } 함수 foo () { 반환 getMyName () } 기능 바 () { ) (foo는 반환 } CONSOLE.LOG (막대 ())

    다른 솔루션 소개 : arguments.callee를 엄격 모드와 Function.prototype.calleris 비표준에서 허용되지 않습니다 엄격한 모드에서 사용할 수 없습니다.


  9. 9.또 다른 사용 사례는 런타임에 바인딩 이벤트 디스패처 수 :

    또 다른 사용 사례는 런타임에 바인딩 이벤트 디스패처 수 :

    MyClass = function () {
      this.events = {};
    
      // Fire up an event (most probably from inside an instance method)
      this.OnFirstRun();
    
      // Fire up other event (most probably from inside an instance method)
      this.OnLastRun();
    
    }
    
    MyClass.prototype.dispatchEvents = function () {
      var EventStack=this.events[GetFunctionName()], i=EventStack.length-1;
    
      do EventStack[i]();
      while (i--);
    }
    
    MyClass.prototype.setEvent = function (event, callback) {
      this.events[event] = [];
      this.events[event].push(callback);
      this["On"+event] = this.dispatchEvents;
    }
    
    MyObject = new MyClass();
    MyObject.setEvent ("FirstRun", somecallback);
    MyObject.setEvent ("FirstRun", someothercallback);
    MyObject.setEvent ("LastRun", yetanothercallback);
    

    여기 장점은 대신이 호출 이름이 암시 제공, 디스패처 쉽게 재사용 할 수 및 인수로 파견 큐를받을 필요가 없습니다입니다 ...

    결국, 일반적인 경우는 "당신이 명시 적으로 통과 할 필요가 없습니다 인수로 함수 이름을 사용하는"것 여기에 제시하고, 그 JQuery와 애니메이션 등, 많은 경우에 유용 할 수있다 () 선택적 콜백, 또는 제한 시간 / 간격 콜백에서 (즉, 당신은 단지 funcion 이름을 전달).


  10. 10.현재 함수 어떻게 얻을 수의 이름은이 질문에 요청 된 이후, 지난 10 년 동안 변경 한 것으로 보인다.

    현재 함수 어떻게 얻을 수의 이름은이 질문에 요청 된 이후, 지난 10 년 동안 변경 한 것으로 보인다.

    지금, 여기, 모두에 대해 지금까지 존재 한 모든 브라우저의 역사를 알고 그것이 2019 크롬 브라우저에서 나를 위해 어떻게 작동 프로 웹 개발자되지 않는 :

    function callerName() {
        return callerName.caller.name;
    }
    function foo() {
        let myname = callerName();
        // do something with it...
    }
    

    다른 답변 중 일부는 엄격한 자바 스크립트 코드와 이것 저것에 대한 몇 가지 크롬 오류에 달렸다.


  11. 11.당신은 함수 foo라는를 작성하고 당신은 당신이 동적으로이 정보를 얻을 필요 할 이유 myfile.js에 알고 있기 때문에?

    당신은 함수 foo라는를 작성하고 당신은 당신이 동적으로이 정보를 얻을 필요 할 이유 myfile.js에 알고 있기 때문에?

    그 존재는 당신이 함수 내에서 arguments.callee.toString를 () (이 전체 기능의 문자열 표현입니다)를 사용하고 함수 이름의 값을 정규식 수 있다고 말했다.

    여기에 자신의 이름을 뱉어 기능입니다 :

    function foo() {
        re = /^function\s+([^(]+)/
        alert(re.exec(arguments.callee.toString())[1]);             
    }
    

  12. 12.내가 여기에 본 것 중 몇 가지 답변의 조합. (FF, 크롬, IE11에서 테스트)

    내가 여기에 본 것 중 몇 가지 답변의 조합. (FF, 크롬, IE11에서 테스트)

    function functionName() 
    {
       var myName = functionName.caller.toString();
       myName = myName.substr('function '.length);
       myName = myName.substr(0, myName.indexOf('('));
       return myName;
    }
    
    function randomFunction(){
        var proof = "This proves that I found the name '" + functionName() + "'";
        alert(proof);
    }
    

    randomFunction ()를 호출하면 함수 이름이 포함 된 문자열을 알려줍니다.

    JS 바이올린 데모 : http://jsfiddle.net/mjgqfhbe/


  13. 13.이 캔에 업데이트 된 대답은이 대답에 이상 찾을 수 있습니다 : https://stackoverflow.com/a/2161470/632495

    이 캔에 업데이트 된 대답은이 대답에 이상 찾을 수 있습니다 : https://stackoverflow.com/a/2161470/632495

    그리고, 당신은 클릭 기분하지 않는 경우 :

    function test() {
      var z = arguments.callee.name;
      console.log(z);
    }
    

  14. 14.정보 2016 올해 실제입니다.

    정보 2016 올해 실제입니다.

    오페라의 결과

    >>> (function func11 (){
    ...     console.log(
    ...         'Function name:',
    ...         arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
    ... })();
    ... 
    ... (function func12 (){
    ...     console.log('Function name:', arguments.callee.name)
    ... })();
    Function name:, func11
    Function name:, func12
    

    크롬에서 결과

    (function func11 (){
        console.log(
            'Function name:',
            arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
    })();
    
    (function func12 (){
        console.log('Function name:', arguments.callee.name)
    })();
    Function name: func11
    Function name: func12
    

    NodeJS에서 결과

    > (function func11 (){
    ...     console.log(
    .....         'Function name:',
    .....         arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
    ... })();
    Function name: func11
    undefined
    > (function func12 (){
    ...     console.log('Function name:', arguments.callee.name)
    ... })();
    Function name: func12
    

    파이어 폭스에서 작동하지 않습니다. IE의 가장자리에 테스트되지 않은.

    NodeJS에서 결과

    > var func11 = function(){
    ...     console.log('Function name:', arguments.callee.name)
    ... }; func11();
    Function name: func11
    

    크롬에서 결과

    var func11 = function(){
        console.log('Function name:', arguments.callee.name)
    }; func11();
    Function name: func11
    

    파이어 폭스, 오페라에서 작동하지 않습니다. IE의 가장자리에 테스트되지 않은.

    메모:

    ~ $ google-chrome --version
    Google Chrome 53.0.2785.116           
    ~ $ opera --version
    Opera 12.16 Build 1860 for Linux x86_64.
    ~ $ firefox --version
    Mozilla Firefox 49.0
    ~ $ node
    node    nodejs  
    ~ $ nodejs --version
    v6.8.1
    ~ $ uname -a
    Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
    

  15. 15.

    (function f() {
        console.log(f.name);  //logs f
    })();
    

    타이프 라이터 변화 :

    function f1() {} 
    function f2(f:Function) {
       console.log(f.name);
    }
    
    f2(f1);  //Logs f1
    

    ES6 / ES2015 준수 엔진에서만 사용할 수 있습니다. 더 참조


  16. 16.여기에 하나의 라이너는 :

    여기에 하나의 라이너는 :

        arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '')
    

    이 같이 :

        function logChanges() {
          let whoami = arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '');
          console.log(whoami + ': just getting started.');
        }
    

  17. 17.이고르 Ostroumov의 답변 이것을 변형 :

    이고르 Ostroumov의 답변 이것을 변형 :

    당신이 매개 변수에 대한 기본값으로 사용하려는 경우, 당신은 '발신자'에 두 번째 수준의 호출을 고려할 필요가있다 :

    function getFunctionsNameThatCalledThisFunction()
    {
      return getFunctionsNameThatCalledThisFunction.caller.caller.name;
    }
    

    이 동적으로 여러 기능의 재사용 구현할 수있다.

    getFunctionsNameThatCalledThisFunction 함수 () { getFunctionsNameThatCalledThisFunction.caller.caller.name를 반환; } 기능 바 (myFunctionName getFunctionsNameThatCalledThisFunction = ()) { 경고 (myFunctionName); } // 팝 - 업 "foo는" 함수 foo () { 바(); } 함수 크로우 () { 바(); } foo는 (); 까마귀();

    당신이 너무 파일 이름을 원하는 경우에, 여기에 또 다른 질문에 F-3000의 도움말을 사용하여 해당 솔루션입니다 :

    function getCurrentFileName()
    {
      let currentFilePath = document.scripts[document.scripts.length-1].src 
      let fileName = currentFilePath.split('/').pop() // formatted to the OP's preference
    
      return fileName 
    }
    
    function bar(fileName = getCurrentFileName(),  myFunctionName = getFunctionsNameThatCalledThisFunction())
    {
      alert(fileName + ' : ' + myFunctionName);
    }
    
    // or even better: "myfile.js : foo"
    function foo()
    {
      bar();
    }
    

  18. 18.시험:

    시험:

    alert(arguments.callee.toString());
    

  19. 19.대답은 짧고 : 경고 (arguments.callee.name);

    대답은 짧고 : 경고 (arguments.callee.name);

  20. from https://stackoverflow.com/questions/1013239/can-i-get-the-name-of-the-currently-running-function-in-javascript by cc-by-sa and MIT license