Javascript get function description

Javascript get function description

The get syntax binds an object property to a function that will be called when that property is looked up. It can also be used in classes.

Try it

Syntax

 get prop()  /* … */ > >  get [expression]()  /* … */ > > 

There are some additional syntax restrictions:

Parameters

The name of the property to bind to the given function. In the same way as other properties in object initializers, it can be a string literal, a number literal, or an identifier.

You can also use expressions for a computed property name to bind to the given function.

Description

Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter.

It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.

Examples

Defining a getter on new objects in object initializers

This will create a pseudo-property latest for object obj , which will return the last array item in log .

const obj =  log: ["example", "test"], get latest()  if (this.log.length === 0) return undefined; return this.log[this.log.length - 1]; >, >; console.log(obj.latest); // "test" 

Note that attempting to assign a value to latest will not change it.

Using getters in classes

You can use the exact same syntax to define public instance getters that are available on class instances. In classes, you don’t need the comma separator between methods.

class ClassWithGetSet  #msg = "hello world"; get msg()  return this.#msg; > set msg(x)  this.#msg = `hello $x>`; > > const instance = new ClassWithGetSet(); console.log(instance.msg); // "hello world" instance.msg = "cake"; console.log(instance.msg); // "hello cake" 

Getter properties are defined on the prototype property of the class and are thus shared by all instances of the class. Unlike getter properties in object literals, getter properties in classes are not enumerable.

Static setters and private setters use similar syntaxes, which are described in the static and private class features pages.

Deleting a getter using the delete operator

If you want to remove the getter, you can just delete it:

Defining a getter on existing objects using defineProperty

To append a getter to an existing object later at any time, use Object.defineProperty() .

const o =  a: 0 >; Object.defineProperty(o, "b",  get()  return this.a + 1; >, >); console.log(o.b); // Runs the getter, which yields a + 1 (which is 1) 

Using a computed property name

const expr = "foo"; const obj =  get [expr]()  return "bar"; >, >; console.log(obj.foo); // "bar" 

Defining static getters

class MyConstants  static get foo()  return "foo"; > > console.log(MyConstants.foo); // 'foo' MyConstants.foo = "bar"; console.log(MyConstants.foo); // 'foo', a static getter's value cannot be changed 

Smart / self-overwriting / lazy getters

Getters give you a way to define a property of an object, but they do not calculate the property’s value until it is accessed. A getter defers the cost of calculating the value until the value is needed. If it is never needed, you never pay the cost.

An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are smart (or memoized) getters. The value is calculated the first time the getter is called, and is then cached so subsequent accesses return the cached value without recalculating it. This is useful in the following situations:

  • If the calculation of a property value is expensive (takes much RAM or CPU time, spawns worker threads, retrieves remote file, etc.).
  • If the value isn’t needed just now. It will be used later, or in some case it’s not used at all.
  • If it’s used, it will be accessed several times, and there is no need to re-calculate that value will never be changed or shouldn’t be re-calculated.

Note: This means that you shouldn’t write a lazy getter for a property whose value you expect to change, because if the getter is lazy then it will not recalculate the value.

Note that getters are not «lazy» or «memoized» by nature; you must implement this technique if you desire this behavior.

In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned.

const obj =  get notifier()  delete this.notifier; this.notifier = document.getElementById("bookmarked-notification-anchor"); return this.notifier; >, >; 

get vs. defineProperty

While using the get keyword and Object.defineProperty() have similar results, there is a subtle difference between the two when used on classes .

When using get the property will be defined on the instance’s prototype, while using Object.defineProperty() the property will be defined on the instance it is applied to.

class Example  get hello()  return "world"; > > const obj = new Example(); console.log(obj.hello); // "world" console.log(Object.getOwnPropertyDescriptor(obj, "hello")); // undefined console.log( Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), "hello"), ); // < configurable: true, enumerable: false, get: function get hello() < return 'world'; >, set: undefined > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 29, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Function: name

The name data property of a Function instance indicates the function’s name as specified when it was created, or it may be either anonymous or » (an empty string) for functions created anonymously.

Try it

Value

Property attributes of Function: name
Writable no
Enumerable no
Configurable yes

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

Description

The function’s name property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself.

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

function someFunction() > someFunction.name = "otherFunction"; console.log(someFunction.name); // someFunction 

The name property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred.

Function declaration

The name property returns the name of a function declaration.

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

Default-exported function declaration

An export default declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is «default» .

// -- someModule.js -- export default function () > // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" 

Function constructor

Functions created with the Function() constructor have name «anonymous».

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

Function expression

If the function expression is named, that name is used as the name property.

const someFunction = function someFunctionName() >; someFunction.name; // "someFunctionName" 

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

However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it’s created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate.

One practical case where the name cannot be inferred is a function returned from another function:

function getFoo()  return () => >; > getFoo().name; // "" 

Variable declaration and method

Variables and methods can infer the name of an anonymous function from its syntactic position.

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

The same applies to assignment:

Initializer and default value

Functions in initializers (default values) of destructuring, default parameters, class fields, etc., will inherit the name of the bound identifier as their name .

const [f = () => >] = []; f.name; // "f" const  someMethod: m = () => > > = >; m.name; // "m" function foo(f = () => >)  console.log(f.name); > foo(); // "f" class Foo  static someMethod = () => >; > Foo.someMethod.name; // someMethod 

Shorthand method

const o =  foo() >, >; o.foo.name; // "foo"; 

Bound function

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

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

Getter and setter

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

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

Class

A class’s name follows the same algorithm as function declarations and expressions.

Warning: JavaScript will set the function’s name property only if a function does not have an own property called name . However, classes’ static members will be set as own properties of the class constructor function, and thus prevent the built-in name from being applied. See an example below.

Symbol as function name

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

const sym1 = Symbol("foo"); const sym2 = Symbol(); const o =  [sym1]() >, [sym2]() >, >; o[sym1].name; // "[foo]" o[sym2].name; // "[]" 

Private property

Private fields and private methods have the hash ( # ) as part of their names.

class Foo  #field = () => >; #method() > getNames()  console.log(this.#field.name); console.log(this.#method.name); > > new Foo().getNames(); // "#field" // "#method" 

Examples

Telling the constructor name of an object

You can use obj.constructor.name to check the «class» of an object.

function Foo() > // Or: class Foo <> const fooInstance = new Foo(); console.log(fooInstance.constructor.name); // "Foo" 

However, because static members will become own properties of the class, we can’t obtain the class name for virtually any class with a static method property name() :

class Foo  constructor() > static name() > > 

With a static name() method Foo.name no longer holds the actual class name but a reference to the name() function object. Trying to obtain the class of fooInstance via fooInstance.constructor.name won’t give us the class name at all, but instead a reference to the static class method. Example:

const fooInstance = new Foo(); console.log(fooInstance.constructor.name); // ƒ name() <> 

Due to the existence of static fields, name may not be a function either.

class Foo  static name = 123; > console.log(new Foo().constructor.name); // 123 

If a class has a static property called name , it will also become writable. The built-in definition in the absence of a custom static definition is read-only:

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

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

JavaScript compressors and minifiers

Warning: Be careful when using the name property with 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() > const foo = new Foo(); if (foo.constructor.name === "Foo")  console.log("'foo' is an instance of 'Foo'"); > else  console.log("Oops!"); > 
function a() > const b = new a(); if (b.constructor.name === "Foo")  console.log("'foo' is an instance of 'Foo'"); > else  console.log("Oops!"); > 

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 the name property, like in the example above, make sure your build pipeline doesn’t change function names, or don’t assume a function has a particular name.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 12, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Читайте также:  Динамический запрос sql java
Оцените статью