README.md (1987B)
1 <!-- 2 3 @license Apache-2.0 4 5 Copyright (c) 2018 The Stdlib Authors. 6 7 Licensed under the Apache License, Version 2.0 (the "License"); 8 you may not use this file except in compliance with the License. 9 You may obtain a copy of the License at 10 11 http://www.apache.org/licenses/LICENSE-2.0 12 13 Unless required by applicable law or agreed to in writing, software 14 distributed under the License is distributed on an "AS IS" BASIS, 15 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 See the License for the specific language governing permissions and 17 limitations under the License. 18 19 --> 20 21 # Read-Only Accessor 22 23 > [Define][@stdlib/utils/define-property] a **read-only** accessor. 24 25 <section class="usage"> 26 27 ## Usage 28 29 ```javascript 30 var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' ); 31 ``` 32 33 #### setReadOnlyAccessor( obj, prop, getter ) 34 35 [Defines][@stdlib/utils/define-property] a **read-only** accessor. 36 37 <!-- run throws: true --> 38 39 ```javascript 40 function getter() { 41 return 'bar'; 42 } 43 44 var obj = {}; 45 46 setReadOnlyAccessor( obj, 'foo', getter ); 47 48 obj.foo = 'boop'; 49 // throws <Error> 50 ``` 51 52 </section> 53 54 <!-- /.usage --> 55 56 <section class="notes"> 57 58 ## Notes 59 60 - Read-only accessors are **enumerable** and **non-configurable**. 61 62 </section> 63 64 <!-- /.notes --> 65 66 <section class="examples"> 67 68 ## Examples 69 70 <!-- eslint no-undef: "error" --> 71 72 ```javascript 73 var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' ); 74 75 function Foo( name ) { 76 if ( !(this instanceof Foo) ) { 77 return new Foo( name ); 78 } 79 setReadOnlyAccessor( this, 'name', getName ); 80 return this; 81 82 function getName() { 83 return name; 84 } 85 } 86 87 var foo = new Foo( 'beep' ); 88 89 try { 90 foo.name = 'boop'; 91 } catch ( err ) { 92 console.error( err.message ); 93 } 94 ``` 95 96 </section> 97 98 <!-- /.examples --> 99 100 <section class="links"> 101 102 [@stdlib/utils/define-property]: https://www.npmjs.com/package/@stdlib/utils/tree/main/define-property 103 104 </section> 105 106 <!-- /.links -->