Search code examples
javascriptprototype

How to get the prototype name inside the function itself?


I'm creating a function for Element and I couldn't find a proper way to get the prototype name itself into it, that's the way I tried, but I don't think it's the most appropriate way, there is some more conventional way to to get the name inside the prototype itself?


Element.prototype.getCssStyle = function getCssStyle(stylePropertyName) {
    var protoName = Element.getCssStyle.name;
 
    return protoName;
}

Solution

  • If your goal is to get the string "getCssStyle"within thegetCssStylefunction, you'd do that by usinggetCssStyle.name`:

    Element.prototype.getCssStyle = function getCssStyle(stylePropertyName) {
        var functionName = getCssStyle.name;
     
        return functionName;
    }
    console.log(document.createElement("div").getCssStyle());

    The name of a function provides an in-scope identifier within the function that refers to the function, and functions have a name property giving their name.

    Or get it from the same place you assigned it, Element.prototype.getCssStyle:

    Element.prototype.getCssStyle = function getCssStyle(stylePropertyName) {
        var functionName = Element.prototype.getCssStyle.name;
     
        return functionName;
    }
    console.log(document.createElement("div").getCssStyle());

    Note that in both cases, this is the name of the function, not necessarily the property you assign it to.


    Side note: I strongly recommend not creating methods on built-in prototypes via direct assignment. It creates enumerable properties on the prototypes, which can mess up naively-written code.

    It's generally best not to add to built-in prototypes at all (and certainly not in library code), but it can be okay-ish in your own app or page code. To do it, use Object.defineProperty

    Object.defineProperty(Element.prototype, "getCssStyle", {
        value: function getCssStyle(stylePropertyName) {
            var functionName = getCssStyle.name;
     
            return functionName;
        },
        enumerable: false,
        configurable: true,
        writable: true,
    });
    console.log(document.createElement("div").getCssStyle());

    The enumerable flag is false by default (all three flags are), but I've included it above for emphasis.