[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/get [Back]  [Original]

getter - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

getter

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 ..

get , .

In this article

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

console.log(obj.latest);
// Expected output: "c"

{get prop() { ... } }
{get [expression]() { ... } }

prop

.

expression

ECMAScript 6, .

, , . JavaScript, .

, , , -.

get:

delete.

- latest obj, .

js
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"

, latest .

delete

, delete:

js
delete obj.latest;

defineProperty

Object.defineProperty().

js
const o = { a: 0 };

Object.defineProperty(o, "b", {
  get: function () {
    return this.a + 1;
  },
});

console.log(o.b); // Runs the getter, which yields a + 1 (which is 1)

: , ECMAScript 6, . .

js
var expr = "foo";

var obj = {
  get [expr]() {
    return "bar";
  },
};

console.log(obj.foo); // "bar"

/ /

, , . , , , .

, . . , . :

  • ( , , , . .).
  • . , .
  • , , , , .

, , , .

. , , , . .

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

Firefox XPCOMUtils.jsm , defineLazyGetter().

get defineProperty

get Object.defineProperty() , Classes .

get , , Object.defineProperty() , .

js
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 }

Specification
ECMAScript 2027 LanguageSpecification
# sec-method-definitions


Web Proxy Viewer  |  New URL  |  Original Page