Path: blob/main/files/en-us/web/javascript/reference/functions/set/index.md
6520 views
------{{jsSidebar("Functions")}}
The set syntax binds an object property to a function to be called when there is an attempt to set that property. It can also be used in classes.
{{EmbedInteractiveExample("pages/js/functions-setter.html")}}
Syntax
There are some additional syntax restrictions:
A setter must have exactly one parameter.
Parameters
prop: The name of the property to bind to the given function. In the same way as other properties in object initializers, it can be a string literal, a number literal, or an identifier.
val: An alias for the variable that holds the value attempted to be assigned to
prop.
expression: 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.
Examples
Defining a setter on new objects in object initializers
The following example define a pseudo-property current of object language. When current is assigned a value, it updates log with that value:
Note that current is not defined, and any attempts to access it will result in undefined.
Using setters in classes
You can use the exact same syntax to define public instance setters that are available on class instances. In classes, you don't need the comma separator between methods.
Setter properties are defined on the prototype property of the class and are thus shared by all instances of the class. Unlike setter properties in object literals, setter properties in classes are not enumerable.
Static setters and private setters use similar syntaxes, which are described in the static and private class features pages.
Removing a setter with the delete operator
If you want to remove the setter, you can just {{jsxref("Operators/delete", "delete")}} it:
Defining a setter on existing objects using defineProperty
To append a setter to an existing object, use {{jsxref("Object.defineProperty()")}}.
Using a computed property name
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
{{jsxref("Operators/delete", "delete")}}
{{jsxref("Object.defineProperty()")}}
Defining getters and setters in JavaScript Guide