Set function name javascript

Function.name

A Function object’s read-only name property indicates the function’s name as specified when it was created, or it may be rather anonymous or » (an empty string) for functions created anonymously.

The source for this interactive example is stored in a GitHub repository. If you’d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Note that in non-standard, pre-ES2015 implementations the configurable attribute was false as well.

JavaScript compressors and minifiers

Warning: Be careful when using Function.name and source code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function’s name at build-time.

function Foo() <>; let foo = new Foo(); if (foo.constructor.name === ‘Foo’) < console.log("'foo' is an instance of 'Foo'"); >else
function a() <>; let b = new a(); if (b.constructor.name === ‘Foo’) < console.log("'foo' is an instance of 'Foo'"); >else

Читайте также:  Check all checkbox html php

In the uncompressed version, the program runs into the truthy-branch and logs «‘foo’ is an instance of ‘Foo'» . Whereas, in the compressed version it behaves differently, and runs into the else-branch. If you rely on Function.name , like in the example above, make sure your build pipeline doesn’t change function names, or don’t assume a function to have a particular name.

Examples

Function statement name

The name property returns the name of a function statement.

function doSomething() <> doSomething.name; // "doSomething"

Function constructor name

Functions created with the syntax new Function(. ) or just Function(. ) create Function objects and their name is «anonymous».

(new Function).name; // "anonymous"

Anonymous function expression

Anonymous function expressions that were created using the keyword function or arrow functions would have «» (an empty string) as their name.

Inferred function names

Variables and methods can infer the name of an anonymous function from its syntactic position (new in ECMAScript 2015).

let f = function() <>; let object = < someMethod: function() <>>; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod"

You can define a function with a name in a function expression:

let object = < someMethod: function object_someMethod() <>>; console.log(object.someMethod.name); // logs "object_someMethod" try < object_someMethod >catch(e) < console.log(e); >// ReferenceError: object_someMethod is not defined

The name property is read-only and cannot be changed by the assigment operator:

Example below contradicts with what is said at the beginning of this section and doesn’t work as described.

let object = < // anonymous someMethod: function() <>>; object.someMethod.name = 'otherMethod'; console.log(object.someMethod.name); // someMethod

Shorthand method names

Bound function names

Function.bind() produces a function whose name is «bound » plus the function name.

function foo() <>; foo.bind(<>).name; // "bound foo"

Function names for getters and setters

When using get and set accessor properties, «get» or «set» will appear in the function name.

let o = < get foo()<>, set foo(x)<> >; var descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo";

Function names in classes

You can use obj.constructor.name to check the «class» of an object (but be sure to read the warnings below):

function Foo() <> // ES2015 Syntax: class Foo <> var fooInstance = new Foo(); console.log(fooInstance.constructor.name); // logs "Foo"

Warning: The script interpreter will set the built-in Function.name property only if a function does not have an own property called name (see section 9.2.11 of the ECMAScript2015 Language Specification). However, ES2015 specifies the static keyword such that static methods will be set as OwnProperty of the class constructor function (ECMAScript2015, 14.5.14.21.b + 12.2.6.9).

Therefore we can’t obtain the class name for virtually any class with a static method property name() :

With a static name() method Foo.name no longer holds the actual class name but a reference to the name() function object. Above class definition in ES2015 syntax will behave in Chrome or Firefox similar to the following snippet in ES5 syntax:

function Foo() <> Object.defineProperty(Foo, 'name', < writable: true >); Foo.name = function() <>;

Trying to obtain the class of fooInstance via fooInstance.constructor.name won’t give us the class name at all but a reference to the static class method. Example:

let fooInstance = new Foo(); console.log(fooInstance.constructor.name); // logs function name()

You may also see from the ES5 syntax example that in Chrome or Firefox our static definition of Foo.name becomes writable. The built-in definition in the absence of a custom static definition is read-only:

Foo.name = 'Hello'; console.log(Foo.name); // logs "Hello" if class Foo has a static name() property but "Foo" if not.

Therefore you may not rely on the built-in Function.name property to always hold a class’s name.

Symbols as function names

If a Symbol is used a function name and the symbol has a description, the method’s name is the description in square brackets.

let sym1 = Symbol("foo"); let sym2 = Symbol(); let o = < [sym1]: function()<>, [sym2]: function()<> >; o[sym1].name; // "[foo]" o[sym2].name; // ""

Specifications

Browser compatibility

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
name Chrome Full support 15 Edge Full support 14 Firefox Full support 1 IE No support No Opera Full support 10.5 Safari Full support 6 WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support 11 Safari iOS Full support 6 Samsung Internet Android Full support 1.0 nodejs Full support Yes
Configurable: true Chrome Full support 43 Edge Full support 14 Firefox Full support 38 IE No support No Opera Full support 30 Safari No support No WebView Android Full support 43 Chrome Android Full support 43 Firefox Android Full support 38 Opera Android Full support 30 Safari iOS No support No Samsung Internet Android Full support 4.0 nodejs ?
Inferred names on anonymous functions Chrome Full support 51 Edge Partial support 14

Legend

Full support Full support Partial support Partial support No support No support Compatibility unknown Compatibility unknown See implementation notes. See implementation notes.

See also

  1. Standard built-in objects
  2. Function
  3. Properties
    1. Function.arguments
    2. Function.caller
    3. Function.displayName
    4. Function.length
    5. Function.name
    1. Function.prototype.apply()
    2. Function.prototype.bind()
    3. Function.prototype.call()
    4. Function.prototype.toSource()
    5. Function.prototype.toString()
    1. Object.prototype.__proto__
    2. Object.prototype.constructor
    1. Object.prototype.__defineGetter__()
    2. Object.prototype.__defineSetter__()
    3. Object.prototype.__lookupGetter__()
    4. Object.prototype.__lookupSetter__()
    5. Object.prototype.hasOwnProperty()
    6. Object.prototype.isPrototypeOf()
    7. Object.prototype.propertyIsEnumerable()
    8. Object.prototype.toLocaleString()
    9. Object.prototype.toSource()
    10. Object.prototype.toString()
    11. Object.prototype.valueOf()
    12. Object.setPrototypeOf()

    Источник

    Mastering JavaScript Function Names: Retrieving, Defining, and Setting

    Learn how to work with function names in JavaScript efficiently. Retrieve and define function names, set them dynamically, and follow best practices.

    JavaScript functions are integral to building dynamic and interactive web applications. They allow developers to write reusable code, improve code organization, and reduce the amount of repetitive code. Understanding how to work with function names in javascript is essential for writing efficient and readable code. In this blog post, we will discuss how to retrieve and set function names in JavaScript.

    Retrieving Function Names

    JavaScript functions have a name property that can be used to retrieve the function’s name. If the function is anonymous, the name property will return an empty string. Anonymous functions must be assigned to a variable to be used. Named functions are hoisted, while anonymous functions are not. Using descriptive names and following naming conventions can make code more readable.

    To retrieve a function’s name, use the name property:

    function exampleFunction() < // function body >console.log(exampleFunction.name); // logs "exampleFunction" 

    If the function is anonymous, the name property will return an empty string:

    const anonymousFunction = function() < // function body >;console.log(anonymousFunction.name); // logs "" 

    To use an anonymous function, it must be assigned to a variable:

    const anonymousFunction = function() < // function body >;anonymousFunction(); // call the anonymous function 

    Defining Function Names

    Functions can be defined with a name using either a function declaration or a named function expression. The function keyword is used to declare a function, and functionName() is used to call a function. Methods are functions that are properties of an object. Arrow functions do not have a name property. Advantages of named functions include easier debugging and more readable code.

    Function Declaration

    A function declaration defines a function with a name:

    function exampleFunction() < // function body >exampleFunction(); // call the exampleFunction 

    Named Function Expression

    A named function expression defines a function with a name:

    const exampleFunction = function functionName() < // function body >;exampleFunction(); // call the exampleFunction 

    Methods

    Methods are functions that are properties of an object. They are defined using an object literal:

    const exampleObject = < exampleMethod: function() < // function body >>;exampleObject.exampleMethod(); // call the exampleMethod 

    Arrow Functions

    Arrow functions do not have a name property:

    const exampleFunction = () => < // function body >;console.log(exampleFunction.name); // logs "" 

    Setting Function Names Dynamically

    The name property is read-only and cannot be changed. To dynamically set a function name, computed property names or constructor functions can be used. The Function constructor can be used to define a function. The arguments.callee property can be used to refer to the current function. Using eval() method to invoke a function whose name is stored in a string variable is not recommended due to security risks and slower performance.

    Computed Property Names

    Computed property names allow for dynamic function names:

    const dynamicFunctionName = "exampleFunction"; const objectWithDynamicFunctionName = < [dynamicFunctionName]: function() < // function body >>;objectWithDynamicFunctionName.exampleFunction(); // call the exampleFunction 

    Constructor Functions

    Constructor functions can be used to define a function with a dynamic name:

    const dynamicFunctionName = "exampleFunction"; const dynamicFunction = new Function( `return function $() <>` );dynamicFunction(); // call the exampleFunction 

    arguments.callee

    The arguments.callee property can be used to refer to the current function:

    const exampleFunction = function() < console.log(arguments.callee.name); // logs "exampleFunction" >;exampleFunction(); // call the exampleFunction 

    Using arguments.callee is not recommended due to performance reasons and has been deprecated in modern JavaScript.

    Best Practices and Tips

    Best practices for function naming include using descriptive names and following naming conventions. Using arrow functions for shorter syntax and using default function parameters to avoid undefined values can make code more efficient. A cheatsheet for working with JavaScript functions can be a helpful reference. Common issues when working with JavaScript functions include scope and variable hoisting. The latest advancements in JavaScript include ES6 features such as arrow functions and template literals .

    Other simple code examples for JavaScript function naming

    In Javascript , for example, create function javascript call by name code example

    window["My"]["Namespace"]["functionName"](arguments); // succeedswindow['test']=new Function('a', 'b', 'return a + b');

    In Javascript case in point, name function in javascript code example

    Conclusion

    Understanding how to work with function names in JavaScript is an essential skill for web developers. Retrieving function names and defining function names using best practices and tips can make code more readable and efficient. Dynamically setting function names can be achieved using computed property names or constructor functions. Best practices include using descriptive names and following naming conventions. Staying up-to-date with the latest advancements in JavaScript can help developers write more efficient code.

    Источник

Оцените статью