static-props
defines static object attributes using Object.defineProperties
Installation | Usage | Annotated source | License
Installation
With npm do
npm install static-props --save
Usage
Let's create a classic Point2d class and add constant attributes.
'use strict' const staticProps = // Or use ES6: import staticProps from 'static-props' { // Suppose you have few static attributes in your class. const color = 'red' // Create a getter. const norm = x * x + y * y // Add constant attributes quickly. label color norm // Add enumerable attributes. const enumerable = true x y enumerable } // Add a static class attribute. dim: 2 const norm = x * x + y * y// A particular case are static methods, since they are functions// they must be wrapped otherwise are considered as getters. norm
After instantiating the class, we can check that its props cannot be changed.
const p = 1 2 // Trying to modify a static prop will throw, as expected.plabel = 'B'// TypeError: Cannot assign to read only property 'label' of #<Point2d>
Props label and color are values, while norm is a getter.
console // 'A'console // 'red'console // 5 = 1 * 1 + 2 * 2
Attributes x
, y
were configured to be enumerable.
console // Point2d { x: 1, y: 2 }
You can access static class attributes and methods.
console // 2console // 5
Annotated source
API is staticProps(obj)(props[, enumerable])
.
Add every prop to obj as not writable nor configurable, i.e. static. If prop is a function use it as a getter, otherwise use it as a value. Finally, apply the Object.defineProperties function.
/** * @param * @returns */ { /** * @param * @param */ return { var staticProps = {} for var propName in props var staticProp = configurable: false enumerable: enumerable var prop = propspropName if typeof prop === 'function' staticPropget = prop else staticPropvalue = prop staticPropwritable = false staticPropspropName = staticProp Object }}
Export function, supporting both CommonJS and ES6.
moduleexports = exportsdefault = staticProps