Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 671251 of setter

  • Revision slug: Web/JavaScript/Reference/Functions/set
  • Revision title: setter
  • Revision id: 671251
  • Created:
  • Creator: fscholz
  • Is current revision? No
  • Comment

Revision Content

{{jsSidebar("Functions")}}

Summary

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) { . . . }}

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

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 o = {
  set current (str) {
    return this.log[this.log.length] = str;
  },
  log: []
}

Note that current is not defined and any attempts to access it will result in undefined.

Defining a setter on existing objects using defineProperty

To append a setter to an existing object later at any time, use {{jsxref("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

Removing a setter with the delete operator

delete o.current;

Specifications

Specification Status Comment
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}} {{Spec2('ES5.1')}} Initial definition.
{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}} {{Spec2('ES6')}}  

Browser compatibility

Based on Robert Nyman's page. No support (notably in IE6-8) means that the script will trigger a syntax error.

{{ CompatibilityTable() }}

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support {{ CompatGeckoDesktop("1.8.1") }} 1 9 9.5 3
Feature Firefox Mobile (Gecko) Android IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

SpiderMonkey-specific notes

  • Starting with JavaScript 1.8.1, setters are no longer called when setting properties in object and array initializers.

See also

  • getter
  • {{jsxref("Operators/delete", "delete")}}
  • {{jsxref("Object.defineProperty()")}}
  • {{jsxref("Object.defineGetter", "__defineGetter__")}}
  • {{jsxref("Object.defineSetter", "__defineSetter__")}}
  • Defining Getters and Setters in JavaScript Guide

Revision Source

<div>
 {{jsSidebar("Functions")}}</div>
<h2 id="Summary">Summary</h2>
<p>The <strong><code>set</code></strong> syntax binds an object property to a function to be called when there is an attempt to set that property.</p>
<h2 id="Syntax">Syntax</h2>
<pre class="syntaxbox">
{set <em>prop</em>(<em>val</em>) { . . . }}</pre>
<h3 id="Parameters">Parameters</h3>
<dl>
 <dt>
  <code>prop</code></dt>
 <dd>
  the name of the property to bind to the given function</dd>
</dl>
<dl>
 <dt>
  <code>val</code></dt>
 <dd>
  an alias for the variable that holds the value attempted to be assigned to <code>prop</code></dd>
</dl>
<h2 id="Description">Description</h2>
<p>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.</p>
<p>Note the following when working with the <code>set</code> syntax:</p>
<div>
 <ul>
  <li><span>It can have an identifier which is either a number or a string;</span></li>
  <li>It must have exactly one parameter (see <a class="external" href="https://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/" rel="external nofollow" target="_blank">Incompatible <abbr title="ECMAScript 5th edition">ES5</abbr> change: literal getter and setter functions must now have exactly zero or one arguments</a> for more information);</li>
  <li>It must not appear in an object literal with another <code>set</code> or with a data entry for the same property.<br />
   ( <code>{ set x(v) { }, set x(v) { } }</code> and <code>{ x: ..., set x(v) { } }</code> are forbidden )</li>
 </ul>
</div>
<p>A setter can be removed using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en-US/docs/JavaScript/Reference/Operators/Special/delete"><code>delete</code></a> operator.</p>
<h2 id="Examples">Examples</h2>
<h3 id="Example:_Defining_a_getter_with_the_get_operator" name="Example:_Defining_a_getter_with_the_get_operator">Defining a setter on new objects in object initializers</h3>
<p>This will define a pseudo-property <code>current</code> of object <code>o</code> that, when assigned a value, will update <code>log</code> with that value:</p>
<pre class="brush: js">
var o = {
  set current (str) {
    return this.log[this.log.length] = str;
  },
  log: []
}
</pre>
<p>Note that <code>current</code> is not defined and any attempts to access it will result in <code>undefined</code>.</p>
<h3 id="Defining_a_setter_on_existing_objects_using_defineProperty">Defining a setter on existing objects using <code>defineProperty</code></h3>
<p>To append a setter to an existing object later at any time, use {{jsxref("Object.defineProperty()")}}.</p>
<pre class="brush: js">
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</pre>
<h3 id="Example:_Removing_a_setter_with_the_delete_operator" name="Example:_Removing_a_setter_with_the_delete_operator">Removing a setter with the <code>delete</code> operator</h3>
<pre class="brush: js">
delete o.current;
</pre>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>Based on <a class="external" href="https://robertnyman.com/javascript/javascript-getters-setters.html#regular-getters-and-setters">Robert Nyman's page</a>. No support (notably in IE6-8) means that the script will trigger a syntax error.</p>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
 <table class="compat-table">
  <tbody>
   <tr>
    <th>Feature</th>
    <th>Firefox (Gecko)</th>
    <th>Chrome</th>
    <th>Internet Explorer</th>
    <th>Opera</th>
    <th>Safari</th>
   </tr>
   <tr>
    <td>Basic support</td>
    <td>{{ CompatGeckoDesktop("1.8.1") }}</td>
    <td>1</td>
    <td>9</td>
    <td>9.5</td>
    <td>3</td>
   </tr>
  </tbody>
 </table>
</div>
<div id="compat-mobile">
 <table class="compat-table">
  <tbody>
   <tr>
    <th>Feature</th>
    <th>Firefox Mobile (Gecko)</th>
    <th>Android</th>
    <th>IE Mobile</th>
    <th>Opera Mobile</th>
    <th>Safari Mobile</th>
   </tr>
   <tr>
    <td>Basic support</td>
    <td>{{ CompatUnknown() }}</td>
    <td>{{ CompatUnknown() }}</td>
    <td>{{ CompatUnknown() }}</td>
    <td>{{ CompatUnknown() }}</td>
    <td>{{ CompatUnknown() }}</td>
   </tr>
  </tbody>
 </table>
</div>
<h3 id="SpiderMonkey-specific_notes">SpiderMonkey-specific notes</h3>
<ul>
 <li>Starting with<a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8.1"> JavaScript 1.8.1</a>, setters are no longer called when setting properties in object and array initializers.</li>
</ul>
<h2 id="See_also" name="See_also">See also</h2>
<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a></li>
 <li>{{jsxref("Operators/delete", "delete")}}</li>
 <li>{{jsxref("Object.defineProperty()")}}</li>
 <li>{{jsxref("Object.defineGetter", "__defineGetter__")}}</li>
 <li>{{jsxref("Object.defineSetter", "__defineSetter__")}}</li>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Defining Getters and Setters</a> in JavaScript Guide</li>
</ul>
Revert to this revision