setter - JavaScript | MDN

archived 14 Apr 2017 15:32:25 UTC
Mozilla is working on a new program for developers and other web builders like you. Help shape that program by taking our 10 minute survey: https://goo.gl/forms/Ync2VuTWwAkQFvJx2
Your Search Results

    setter

    The set syntax binds an object property to a function to be called when there is an attempt to set that property.

    Syntax

    {set prop(val) { . . . }}
    {set [expression](val) { . . . }}

    Parameters

    prop
    The name of the property to bind to the given function.
    val
    An alias for the variable that holds the value attempted to be assigned to prop.
    expression
    Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function.

    Description

    In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.
    Note the following when working with the set syntax:
    A setter can be removed using the delete operator.

    Examples

    Defining a setter on new objects in object initializers

    This will define a pseudo-property current of object o that, when assigned a value, will update log with that value:
    var language = {
      set current(name) {
        this.log.push(name);
      },
      log: []
    }
    
    language.current = 'EN';
    console.log(language.log); // ['EN']
    
    language.current = 'FA';
    console.log(language.log); // ['EN', 'FA']
    Note that current is not defined and any attempts to access it will result in undefined.

    Removing a setter with the delete operator

    If you want to remove the setter, you can just delete it:
    delete o.current;

    Defining a setter on existing objects using defineProperty

    To append a setter to an existing object later at any time, use Object.defineProperty().
    var o = {a: 0};
    
    Object.defineProperty(o, 'b', { set: function(x) { this.a = x / 2; } });
    
    o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
    console.log(o.a) // 5

    Using a computed property name

    var expr = 'foo';
    
    var obj = {
      baz: 'bar',
      set [expr](v) { this.baz = v; }
    };
    
    console.log(obj.baz); // "bar"
    obj.foo = 'baz';      // run the setter
    console.log(obj.baz); // "baz"

    Specifications

    Specification Status Comment
    ECMAScript 5.1 (ECMA-262)
    The definition of 'Object Initializer' in that specification.
    STStandard Initial definition.
    ECMAScript 2015 (6th Edition, ECMA-262)
    The definition of 'Method definitions' in that specification.
    STStandard Added computed property names.
    ECMAScript 2017 Draft (ECMA-262)
    The definition of 'Method definitions' in that specification.
    DDraft  

    Browser compatibility

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support 1 2.0 (1.8.1) 9 9.5 3
    Computed property names No support 34 (34) No support No support No support
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support (Yes) (Yes) 1.0 (1.8.1) (Yes) (Yes) (Yes)
    Computed property names No support No support 34.0 (34.0) No support No support No support

    SpiderMonkey-specific notes

    • Starting with JavaScript 1.8.1, setters are no longer called when setting properties in object and array initializers.
    • From SpiderMonkey 38 on, a setter with a rest parameter is a SyntaxError as per the ES2015 specification.

    See also

    Document Tags and Contributors

     Last updated by: nmve,

    Thanks! Please check your inbox to confirm your subscription.

    If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.
    See also
    1. JavaScript
    2. Tutorials:
    3. Complete beginners
      1. JavaScript basics
      2. JavaScript first steps
      3. JavaScript building blocks
      4. Introducing JavaScript objects
    4. JavaScript Guide
      1. Introduction
      2. Grammar and types
      3. Control flow and error handling
      4. Loops and iteration
      5. Functions
      6. Expressions and operators
      7. Numbers and dates
      8. Text formatting
      9. Regular expressions
      10. Indexed collections
      11. Keyed collections
      12. Working with objects
      13. Details of the object model
      14. Iterators and generators
      15. Meta programming
    5. Intermediate
      1. A re-introduction to JavaScript
      2. JavaScript data structures
      3. Equality comparisons and sameness
      4. Closures
    6. Advanced
      1. Inheritance and the prototype chain
      2. Strict mode
      3. JavaScript typed arrays
      4. SIMD types
      5. Memory Management
      6. Concurrency model and Event Loop
    7. References:
    8. Built-in objects
      1. Array
      2. ArrayBuffer
      3. AsyncFunction
      4. Atomics
      5. Boolean
      6. DataView
      7. Date
      8. Error
      9. EvalError
      10. Float32Array
      11. Float64Array
      12. Function
      13. Generator
      14. GeneratorFunction
      15. Infinity
      16. Int16Array
      17. Int32Array
      18. Int8Array
      19. InternalError
      20. Intl
      21. Intl.Collator
      22. Intl.DateTimeFormat
      23. Intl.NumberFormat
      24. Iterator
      25. JSON
      26. Map
      27. Math
      28. NaN
      29. Number
      30. Object
      31. ParallelArray
      32. Promise
      33. Proxy
      34. RangeError
      35. ReferenceError
      36. Reflect
      37. RegExp
      38. SIMD
      39. SIMD.Bool16x8
      40. SIMD.Bool32x4
      41. SIMD.Bool64x2
      42. SIMD.Bool8x16
      43. SIMD.Float32x4
      44. SIMD.Float64x2
      45. SIMD.Int16x8
      46. SIMD.Int32x4
      47. SIMD.Int8x16
      48. SIMD.Uint16x8
      49. SIMD.Uint32x4
      50. SIMD.Uint8x16
      51. Set
      52. SharedArrayBuffer
      53. StopIteration
      54. String
      55. Symbol
      56. SyntaxError
      57. TypeError
      58. TypedArray
      59. URIError
      60. Uint16Array
      61. Uint32Array
      62. Uint8Array
      63. Uint8ClampedArray
      64. WeakMap
      65. WeakSet
      66. WebAssembly
      67. decodeURI()
      68. decodeURIComponent()
      69. encodeURI()
      70. encodeURIComponent()
      71. escape()
      72. eval()
      73. isFinite()
      74. isNaN()
      75. null
      76. parseFloat()
      77. parseInt()
      78. undefined
      79. unescape()
      80. uneval()
    9. Expressions & operators
      1. Arithmetic operators
      2. Array comprehensions
      3. Assignment operators
      4. Bitwise operators
      5. Comma operator
      6. Comparison operators
      7. Conditional (ternary) Operator
      8. Destructuring assignment
      9. Expression closures
      10. Generator comprehensions
      11. Grouping operator
      12. Legacy generator function expression
      13. Logical Operators
      14. Object initializer
      15. Operator precedence
      16. Property accessors
      17. Spread syntax
      18. async function expression
      19. await
      20. class expression
      21. delete operator
      22. function expression
      23. function* expression
      24. in operator
      25. instanceof
      26. new operator
      27. new.target
      28. super
      29. this
      30. typeof
      31. void operator
      32. yield
      33. yield*
    10. Statements & declarations
      1. Legacy generator function
      2. async function
      3. block
      4. break
      5. class
      6. const
      7. continue
      8. debugger
      9. default
      10. do...while
      11. empty
      12. export
      13. for
      14. for each...in
      15. for...in
      16. for...of
      17. function
      18. function*
      19. if...else
      20. import
      21. label
      22. let
      23. return
      24. switch
      25. throw
      26. try...catch
      27. var
      28. while
      29. with
    11. Functions
      1. Arguments object
      2. Arrow functions
      3. Default parameters
      4. Method definitions
      5. Rest parameters
      6. getter
      7. setter
    12. Classes
      1. constructor
      2. extends
      3. static
    13. Errors
      1. Error: Permission denied to access property "x"
      2. InternalError: too much recursion
      3. RangeError: argument is not a valid code point
      4. RangeError: invalid array length
      5. RangeError: precision is out of range
      6. RangeError: radix must be an integer
      7. RangeError: repeat count must be less than infinity
      8. RangeError: repeat count must be non-negative
      9. ReferenceError: "x" is not defined
      10. ReferenceError: assignment to undeclared variable "x"
      11. ReferenceError: deprecated caller or arguments usage
      12. ReferenceError: invalid assignment left-hand side
      13. ReferenceError: reference to undefined property "x"
      14. SyntaxError: "use strict" not allowed in function with non-simple parameters
      15. SyntaxError: "x" is not a legal ECMA-262 octal constant
      16. SyntaxError: JSON.parse: bad parsing
      17. SyntaxError: Malformed formal parameter
      18. SyntaxError: Unexpected token
      19. SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
      20. SyntaxError: missing ) after argument list
      21. SyntaxError: missing ; before statement
      22. SyntaxError: missing ] after element list
      23. SyntaxError: missing } after property list
      24. SyntaxError: redeclaration of formal parameter "x"
      25. SyntaxError: return not in function
      26. SyntaxError: test for equality (==) mistyped as assignment (=)?
      27. SyntaxError: unterminated string literal
      28. TypeError: "x" has no properties
      29. TypeError: "x" is (not) "y"
      30. TypeError: "x" is not a constructor
      31. TypeError: "x" is not a function
      32. TypeError: "x" is read-only
      33. TypeError: More arguments needed
      34. TypeError: invalid Array.prototype.sort argument
      35. TypeError: property "x" is non-configurable and can't be deleted
      36. TypeError: variable "x" redeclares argument
      37. Warning: -file- is being assigned a //# sourceMappingURL, but already has one
      38. Warning: JavaScript 1.6's for-each-in loops are deprecated
      39. Warning: unreachable code after return statement
    14. Misc
      1. JavaScript technologies overview
      2. Lexical grammar
      3. JavaScript data structures
      4. Enumerability and ownership of properties
      5. Iteration protocols
      6. Strict mode
      7. Transitioning to strict mode
      8. Template literals
      9. Deprecated features
    15. New in JavaScript
      1. ECMAScript 2015 support in Mozilla
      2. ECMAScript 5 support in Mozilla
      3. ECMAScript Next support in Mozilla
      4. Firefox JavaScript changelog
      5. New in JavaScript 1.1
      6. New in JavaScript 1.2
      7. New in JavaScript 1.3
      8. New in JavaScript 1.4
      9. New in JavaScript 1.5
      10. New in JavaScript 1.6
      11. New in JavaScript 1.7
      12. New in JavaScript 1.8
      13. New in JavaScript 1.8.1
      14. New in JavaScript 1.8.5
    16. Documentation:
    17. Useful lists
      1. All pages index
      2. Methods index
      3. Properties index
      4. Pages tagged "JavaScript"
    18. Contribute
      1. JavaScript doc status
      2. The MDN project
    0%
    10%
    20%
    30%
    40%
    50%
    60%
    70%
    80%
    90%
    100%