JS Built-ins
ObjectObject.definePropertyadvanced

Object.defineProperty() β€” getter descriptor

πŸ“– Usage Example
// Define a property with a custom descriptor
const obj = {}
Object.defineProperty(obj, 'name', {
  value: 'Alice',
  writable: false,
  enumerable: true,
})

Use Object.defineProperty() to add or modify a property with precise control over its writability, enumerability, and configurability.

Object.defineProperty() β€” accessor descriptor

An accessor descriptor uses get (and optionally set) instead of value/writable. The getter runs every time the property is read.

Challenge: Implement addGetter(obj, key, fn) that defines a getter using Object.defineProperty.

const o = { _n: 5 }
addGetter(o, 'double', function() { return this._n * 2 })
o.double // β†’ 10
πŸ’‘ Hints (2)
  • β€’ Use `{ get: fn }` in the descriptor. Do NOT include `value` or `writable` β€” they conflict with `get`.
  • β€’ The getter function receives `this` as the object the property is accessed on.