Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

define-accessor-property

ljharb10.9kMIT1.0.0TypeScript support: included

Define an accessor property on an object. Will either throw, or fall back to assignment in loose mode, in an engine without descriptors.

define, data, property, object, accessor, javascript, ecmascript, enumerable, configurable, writable

readme

define-accessor-property Version Badge

github actions coverage License Downloads

npm badge

Define an accessor property on an object. In an engine without descriptors, in loose mode, when only a getter is provided, nonEnumerable is false, and nonConfigurable is false, wil fall back to assignment - otherwise, it will throw.

The two non* options can also be passed null, which will use the existing state if available.

The loose option will mean that if you attempt to set a nonconfigurable/nonwritable accessor property with set, in an environment without descriptor support, it will fall back to normal assignment (and eagerly evaluate the getter).

Usage

var defineAccessorProperty = require('define-accessor-property');
var assert = require('assert');

var str = 'value';
var strThunk = function () { return str; };
var strSetter = function (v) { str = v; };
var random = function () { return Math.random(); };

var obj = {};
defineAccessorProperty(
    obj,
    'key',
    {
        get: strThunk,
        set: strSetter,
    }
);
defineAccessorProperty(
    obj,
    'key2',
    {
        get: random, // at least one of "get" or "set" must be provided
        nonConfigurable: true, // optional
        nonEnumerable: true, // optional
        loose: false, // optional
    }
);

assert.deepEqual(
    Object.getOwnPropertyDescriptors(obj),
    {
        key: {
            configurable: true,
            enumerable: true,
            get: strThunk,
            set: strSetter,
        },
        key2: {
            configurable: false,
            enumerable: false,
            get: random,
            set: undefined,
        },
    }
);

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

v1.0.0 - 2024-02-16

Commits