문제

이것을 할 수 있습니까 :

myfile.js:
function foo() {
    alert(<my-function-name>);
    // pops-up "foo"
    // or even better: "myfile.js : foo"
}

내 스택에 Dojo와 JQuery 프레임 워크가 있으므로 더 쉽게 사용하면 사용할 수 있습니다.

도움이 되었습니까?

해결책

사용하여 얻을 수 있어야합니다 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);
}

원천: JavaScript- 현재 함수 이름을 얻습니다.

다른 팁

비 표식 기능의 경우

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

그러나 오류 핸들러의 경우 결과는 오류 처리기 기능의 이름일까요?

필요한 것은 간단합니다. 기능 작성 :

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

필요할 때마다 간단히 사용합니다.

function foo() { 
  console.log(getFuncName())
}

foo() 
// Logs: "foo"

에 따르면 MDN

경고: ECMAScript (ES5)의 제 5 판은 엄격한 모드에서 arguments.callee ()의 사용을 금지합니다. arguments.callee ()를 사용하지 않으면 함수 표현식에 이름을 제시하거나 함수가 호출 해야하는 함수 선언을 사용하십시오.

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

이렇게해야합니다.

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

발신자의 경우 사용하십시오 caller.toString().

이것은 "세계에서 가장 추악한 해킹"의 범주에 들어가야하지만 여기에서갑니다.

먼저, 이름을 인쇄합니다 현재의 기능 (다른 답변에서와 같이)은 기능이 무엇인지 이미 알고 있기 때문에 나에게 제한된 사용이있는 것 같습니다!

그러나 이름을 찾으십시오 부름 기능은 추적 기능에 매우 유용 할 수 있습니다. 이것은 regexp와 함께 있지만 indexof를 사용하는 것은 약 3 배 더 빠릅니다.

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

function me() {
    console.log( getFunctionName() );
}

me();

다음은 작동하는 방법입니다.

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);
  });

});

세 번째 테스트는 테스트가 /util /functions에있는 경우에만 작동합니다.

다른 사용 사례는 런타임에 바인딩 된 이벤트 디스패처 일 수 있습니다.

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 animate () 옵션 콜백과 같은 많은 경우에 유용 할 수 있습니다. 또는 타임 아웃/간격 콜백 (즉, funcion 이름 만 전달).

그만큼 getMyName 아래 스 니펫에서 함수는 호출 함수의 이름을 반환합니다. 해킹이고 의존합니다 비표준 특징: Error.prototype.stack. 문자열의 형식은 다음과 같습니다 Error.prototype.stack 다른 엔진에서 다르게 구현되므로 어디에서나 작동하지 않을 것입니다.

function getMyName() {
  var e = new Error('dummy');
  var stack = e.stack
                .split('\n')[2]
                // " at functionName ( ..." => "functionName"
                .replace(/^\s+at\s+(.+?)\s.+/g, '$1' );
                return stack
}

function foo(){
  return getMyName()
}

function bar() {
  return foo()
}

console.log(bar())

다른 솔루션에 대해 : arguments.callee 엄격한 모드에서는 허용되지 않습니다 그리고 Function.prototype.caller~이다 비표준 및 엄격한 모드에서는 허용되지 않습니다.

이름이 지정된 함수를 작성 했으므로 foo 그리고 당신은 그것이 있다는 것을 알고 있습니다 myfile.js 이 정보를 동적으로 가져와야하는 이유는 무엇입니까?

그것은 당신이 사용할 수 있다고 말합니다 arguments.callee.toString() 함수 내부 (이것은 전체 함수의 문자열 표현) 및 함수 이름의 값을 다시 설명합니다.

다음은 자체 이름을 뱉어내는 기능입니다.

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

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

그리고 클릭하고 싶지 않다면 :

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

정보는 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

Firefox에서는 작동하지 않습니다. 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

Firefox, Opera에서는 작동하지 않습니다. IE와 가장자리에 테스트되지 않았습니다.

메모:

  1. 익명 기능은 확인하는 것이 합리적이지 않습니다.
  2. 테스트 환경

~ $ 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

내가 여기서 본 몇 가지 응답의 조합. (FF, Chrome, 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/

여기에 하나의 라이너가 있습니다.

    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.');
    }
(function f() {
    console.log(f.name);  //logs f
})();

TypeScript 변형 :

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

f2(f1);  //Logs f1

참고 ES6/ES2015 호환 엔진에서만 사용할 수 있습니다. 더 보려면

이것은 변형입니다 Igor Ostoumov 's 대답:

매개 변수의 기본값으로 사용하려면 '발신자'에 대한 두 번째 레벨 호출을 고려해야합니다.

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

이를 통해 여러 기능에서 재사용 가능한 구현이 동적으로 허용됩니다.

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

function bar(myFunctionName = getFunctionsNameThatCalledThisFunction())
{ 
  alert(myFunctionName);
}

// pops-up "foo"
function foo()
{
  bar();
}

function crow()
{
  bar();
}

foo();
crow();

파일 이름도 원한다면 여기에서 답을 사용하는 솔루션이 있습니다. 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();
}

노력하다:

alert(arguments.callee.toString());

대답은 짧습니다. alert(arguments.callee.name);

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top