Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

get

BaselineWidely available

Theget syntax binds an object property to a function that will be called when that property is looked up. It can also be used inclasses.

Try it

const obj = {  log: ["a", "b", "c"],  get latest() {    return this.log[this.log.length - 1];  },};console.log(obj.latest);// Expected output: "c"

Syntax

js
{ get prop() { /* … */ } }{ get [expression]() { /* … */ } }

There are some additional syntax restrictions:

  • A getter must have exactly zero parameters.

Parameters

prop

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

expression

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 agetter.

An object property is either a data property or an accessor property, but it cannot simultaneously be both. ReadObject.defineProperty() for more information. The getter syntax allows you to specify the getter function in an object initializer.

js
const obj = {  get prop() {    // getter, the code executed when reading obj.prop    return someValue;  },};

Properties defined using this syntax are own properties of the created object, and they are configurable and enumerable.

Examples

Defining a getter on new objects in object initializers

This will create a pseudo-propertylatest for objectobj,which will return the last array item inlog.

js
const obj = {  log: ["example", "test"],  get latest() {    return this.log.at(-1);  },};console.log(obj.latest); // "test"

Note that attempting to assign a value tolatest 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.

js
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 theprototype 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 getters and private getters use similar syntaxes, which are described in thestatic andprivate elements pages.

Deleting a getter using thedelete operator

If you want to remove the getter, you can justdeleteit:

js
delete obj.latest;

Defining a getter on existing objects usingdefineProperty

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

js
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

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

Defining static getters

js
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 todefine a property of an object, but they do notcalculate the property's value until it is accessed. A getter defers the costof calculating the value until the value is needed. If it is never needed, you never paythe cost.

An additional optimization technique to lazify or delay the calculation of a propertyvalue and cache it for later access aresmart (ormemoized) getters.The value is calculated the first time the getter is called and is then cached sosubsequent accesses return the cached value without recalculating it. This is useful inthe 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 cases, it's notused at all.
  • If it's used, it will be accessed several times, and there is no need tore-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 youexpect to change, because if the getter is lazy, then it will not recalculate thevalue.

Note that getters are not "lazy" or "memoized" by nature; you must implement thistechnique if you desire this behavior.

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

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

get vs. defineProperty

While using theget keyword andObject.defineProperty() havesimilar results, there is a subtle difference between the two when used onclasses.

When usingget the property will be defined on the instance's prototype,while usingObject.defineProperty() the property will be defined on theinstance it is applied to.

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

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-method-definitions

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp