Skip to content

Methods in classes are anonymous function on es3/es5 target #16141

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
TobiasSekan opened this issue May 30, 2017 · 1 comment
Closed

Methods in classes are anonymous function on es3/es5 target #16141

TobiasSekan opened this issue May 30, 2017 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@TobiasSekan
Copy link

TobiasSekan commented May 30, 2017

When target is es3 or es5 method inside classes will reduced to anonymous function so it is impossible to get the name of the function, when it is used as parameter.

TypeScript Version: 2.2

Code

export class MyClass
{
  public MyFunction(myParam: string)
}

Expected behavior: (named function)

    var MyClass = (function () {
        function MyClass() {
        }
        MyClass.prototype.MyFunction = function MyFunction(myParam) {
            return myParam;
        };
        return MyClass;
    }());
    exports.default = MyClass;

Actual behavior: (anonymous function)

    var MyClass = (function () {
        function MyClass() {
        }
        MyClass.prototype.MyFunction = function (myParam) {
            return myParam;
        };
        return MyClass;
    }());
    exports.default = MyClass;

Function to get the method name
(parameter has type any, because the name attribute is missing in Function type)

    /**
     * Return the name of a given function
     * @param {Function} functionSource The function
     * @returns {string} The name of the function
     */
    public static GetFunctionName(functionSource: any): string
    {
        if(functionSource.name)
        {
            return functionSource.name;
        }

        let funcNameRegex = new RegExp(/function (.{1,})\(/);
        let results       = funcNameRegex.exec(functionSource.toString());
        let result        = results && results.length > 1 && results[1];

        if(!result)
        {
            funcNameRegex = new RegExp(/return .([^;]+)/);
            results       = funcNameRegex.exec(functionSource.toString());
            result        = results && results.length > 1 && results[1].split(".").pop();
        }

        return result || "";
    }
@mhegazy
Copy link
Contributor

mhegazy commented May 30, 2017

Duplicate of #5611

@mhegazy mhegazy added the Duplicate An existing issue was already created label May 30, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants