Property descriptors should be defined properly

  • BAD_PROPERTY_DESCRIPTOR
  • Error
  • High
  • No tags

This rule applies when an invalid property descriptor is used at Object.defineProperty() or Object.defineProperties().

Property descriptors can define either a regular data property or an accessor property having a getter or setter function.

When defining an accessor, caution is needed as TypeError exceptions occur in the following cases:

  1. The getter or setter is specified with a non-function value except undefined.
  2. A value or writable attribute which applies only to data descriptors is also specified.

Note that the writable attribute is meaningless for an accessor because an accessor is inherently non-writable when the setter is not defined.

Noncompliant Code Example

View with compliant examples side by side
// Example 1
Object.defineProperty(obj, "prop1", {
    get: 42, // BAD_PROPERTY_DESCRIPTOR alarm because '42' is not a function.
    set: function (x) {
        doSomething(x);
    }
});

// Example 2
Object.defineProperty(obj, "prop2", {
    get: function() {
        return 42;
    },
    writable: false // BAD_PROPERTY_DESCRIPTOR alarm because 'writable' cannot be specified for an accessor.
});

Compliant Code Example

View with noncompliant examples side by side
// Example 1
Object.defineProperty(obj, "prop1", {
    get: function () {
        return 42;
    },
    set: function (x) {
        doSomething(x);
    }
});

// Example 2
Object.defineProperty(obj, "prop2", {
    get: function() {
        return 42;
    }
});

Version

This rule was introduced in DeepScan 1.32.0.

See