Proxy

  • Revision slug: JavaScript/Reference/Global_Objects/Proxy
  • Revision title: Proxy
  • Revision id: 374421
  • Created:
  • Creator: fusionchess
  • Is current revision? No
  • Comment A complete traps list example

Revision Content

{{ gecko_minversion_header("18.0") }}

{{ Non-standard_header() }}

{{ warning("The SpiderMonkey Proxy implementation is a prototype and the Proxy API and semantics specifications are unstable. The SpiderMonkey implementation may not reflect the latest specification draft. It is subject to change anytime. It is provided as an experimental feature. Do not rely on it for production code.") }}

{{warning("This page describes the new API (called 'direct_proxies') which is part of Firefox 18. For the previous API (Firefox 17 and below), visit the old proxy API page")}}

Introduction

Proxies are objects for which the programmer has to define the semantics in JavaScript. The default object semantics are implemented in the JavaScript engine, often written in lower-level languages like C++. Proxies let the programmer define most of the behavior of an object in JavaScript. They are said to provide a meta-programming API.

Terminology

catch-all mechanism (or "intercession API")
The technical term for this feature.
proxy
The object whose accesses are being intercepted.
handler
Placeholder object which contains traps.
traps
The methods that provide property access. This is analogous to the concept of traps in operating systems.
target
Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants regarding object non-extensibility or non-configurable properties are verified against the target.

Proxy API

Proxies are new objects; it's not possible to "proxyfy" an existing object. Here is how to create a proxy

var p = new Proxy(target, handler);

Where:

  • target is an object (can be any sort of objects, including a native array, a function or even another proxy).
  • handler is an object whose properties are functions which define the behavior of the proxy when an operation is performed on it.

Handler API

All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.

JavaScript code Handler method Description
Object.getOwnPropertyDescriptor(proxy, name) getOwnPropertyDescriptor
function(target, name) -> PropertyDescriptor | undefined
Should return a valid property descriptor object, or undefined to indicate that no property named name exists in the emulated object.
Object.getOwnPropertyNames(proxy) getOwnPropertyNames function(target) -> [String] Return an array of all own (non-inherited) property names of the emulated object.
Object.defineProperty(proxy,name,pd) defineProperty function(target, name, propertyDescriptor) -> any Define a new property whose attributes are determined by the given propertyDescriptor. The return value of this method is ignored.
delete proxy.name deleteProperty function(target, name) -> boolean Delete the named property from the proxy. The boolean return value of this method should indicate whether or not the name property was successfully deleted.
Object.freeze(proxy) freeze function(target) -> boolean Freezes the object. The boolean indicates whether the operation was successful
Object.seal(proxy) seal function(target) -> boolean Seals the object. The boolean indicates whether the operation was successful
Object.preventExtensions(proxy) preventExtensions function(target) -> boolean Makes the object non-extensible. The boolean indicates whether the operation was successful
name in proxy has function(target, name) -> boolean  
Object.prototype.hasOwnProperty.call(proxy, name) hasOwn function(target, name) -> boolean  

proxy.name (in the context of "getting the value")

receiver.name (if receiver inherits from a proxy and does not override name)

get function(target, name, receiver) -> any receiver is either the proxy or an object that inherits from the proxy.

proxy.name = val (in the context of "setting the value")

receiver.name = val (if receiver inherits from a proxy and does not override name)

set function(target, name, val, receiver) -> boolean receiver is either the proxy or an object that inherits from the proxy.
for(prop in proxy){...} enumerate function(target) -> [String] From the proxy user point of view, properties appear in the for..in loop in the same order as they are in the returned array. Known bug: for for..in loops, the iterate trap is called while it should be the enumerate trap
for(prop of proxy){...} iterate function(target) -> iterator  
Object.keys(proxy) keys function(target) -> [String]  
proxy.apply(thisValue, args) apply function(target, thisValue, args) -> any  
new proxy(...args) construct function(target, args) -> any  

Invariants

Even though proxies provide a lot of power to users, some operations are not trapped in order to keep the language consistent:

  • The double and triple equal (==, ===) operator is not trapped. p1 === p2 if and only if p1 and p2 refer to the same proxy.
  • Object.getPrototypeOf(proxy) unconditionally returns Object.getPrototypeOf(target)
  • typeof proxy unconditionally returns typeof target
  • Object.prototype.toString.call(proxy) unconditionally returns Object.prototype.toString.call(target)

Examples

Very simple example

An object with 37 as its default value when the property name is not in the object

var handler = {
    get: function(target, name){
        return name in target?
            target[name] :
            37;
    }
};

var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;

console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37

No-op forwarding proxy

In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it.

var target = {};
var p = new Proxy(target, {});

p.a = 37; // operation forwarded to the proxy

console.log(target.a); // 37. The operation has been properly forwarded

Validation

With a Proxy, you can easily validate the passed value for an object.

let validator = {
  set: function(obj, prop, value) {
    if (prop === 'age') {
      if (!Number.isInteger(value)) {
        throw new TypeError('The age is not an integer');
      }
      if (value > 200) {
        throw new RangeError('The age seems invalid');
      }
    }

    // The default behavior to store the value
    obj[prop] = value;
  }
};

let person = new Proxy({}, validator);

person.age = 100;
console.log(person.age); // 100
person.age = 'young'; // Throws an exception
person.age = 300; // Throws an exception

Manipulating DOM nodes

Sometimes you want to toggle the attribute or class name of two different elements. Here's how:

let view = new Proxy({
  selected: null
},
{
  set: function(obj, prop, newval) {
    let oldval = obj[prop];

    if (prop === 'selected') {
      if (oldval) {
        oldval.setAttribute('aria-selected', 'false');
      }
      if (newval) {
        newval.setAttribute('aria-selected', 'true');
      }
    }

    // The default behavior to store the value
    obj[prop] = newval;
  }
});

let i1 = view.selected = document.getElementById('item-1');
console.log(i1.getAttribute('aria-selected')); // 'true'

let i2 = view.selected = document.getElementById('item-2');
console.log(i1.getAttribute('aria-selected')); // 'false'
console.log(i2.getAttribute('aria-selected')); // 'true'

Value correction and an extra property

The products proxy object evaluates the passed value and convert it to an array if needed. The object also supports an extra property called latestBrowser both as a getter and a setter.

let products = new Proxy({
  browsers: ['Internet Explorer', 'Netscape']
},
{
  get: function(obj, prop) {
    // An extra property
    if (prop === 'latestBrowser') {
      return obj.browsers[obj.browsers.length - 1];
    }

    // The default behavior to return the value
    return obj[prop];
  },
  set: function(obj, prop, value) {
    // An extra property
    if (prop === 'latestBrowser') {
      obj.browsers.push(value);
      return;
    }

    // Convert the value if it is not an array
    if (typeof value === 'string') {
      value = [value];
    }

    // The default behavior to store the value
    obj[prop] = value;
  }
});

console.log(products.browsers); // ['Internet Explorer', 'Netscape']
products.browsers = 'Firefox'; // pass a string (by mistake)
console.log(products.browsers); // ['Firefox'] <- no problem, the value is an array

products.latestBrowser = 'Chrome';
console.log(products.browsers); // ['Firefox', 'Chrome']
console.log(products.latestBrowser); // 'Chrome'

Finding an array item object by its property

This proxy extends an array with some utility features. As you see, you can flexibly "define" properties without using Object.defineProperties. This example can be adapted to find a table row by its cell. In that case, the target will be table.rows.

let products = new Proxy([
  { name: 'Firefox', type: 'browser' },
  { name: 'SeaMonkey', type: 'browser' },
  { name: 'Thunderbird', type: 'mailer' }
],
{
  get: function(obj, prop) {
    // The default behavior to return the value; prop is usually an integer
    if (prop in obj) {
      return obj[prop];
    }

    // Get the number of products; an alias of products.length
    if (prop === 'number') {
      return obj.length;
    }

    let result, types = {};

    for (let product of obj) {
      if (product.name === prop) {
        result = product;
      }
      if (types[product.type]) {
        types[product.type].push(product);
      } else {
        types[product.type] = [product];
      }
    }

    // Get a product by name
    if (result) {
      return result;
    }

    // Get products by type
    if (prop in types) {
      return types[prop];
    }

    // Get product types
    if (prop === 'types') {
      return Object.keys(types);
    }

    return undefined;
  }
});

console.log(products[0]); // { name: 'Firefox', type: 'browser' }
console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' }
console.log(products['Chrome']); // undefined
console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
console.log(products.types); // ['browser', 'mailer']
console.log(products.number); // 3

A complete traps list example

In order to create a complete sample traps list, now we will proxify the docCookies global object of the "little framework" published on the document.cookie page.

/* get the "docCookies" object here: https://developer.mozilla.org/en-US/docs/DOM/document.cookie */

var docCookies = new Proxy(docCookies, {
  "get": function (oTarget, sKey) {
    return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
  },
  "set": function (oTarget, sKey, vValue) {
    if (sKey in oTarget) { return false; }
    oTarget.setItem(sKey, vValue.toString());
    return true;
  },
  "delete": function (oTarget, sKey) {
    if (sKey in oTarget) { return false; }
    oTarget.removeItem(sKey);
    return true;
  },
  "enumerate": function (oTarget, sKey) {
    return oTarget.keys();
  },
  "iterate": function (oTarget, sKey) {
    return oTarget.keys();
  },
  "keys": function (oTarget, sKey) {
    return oTarget.keys();
  },
  "has": function (oTarget, sKey) {
    return sKey in oTarget || oTarget.hasItem(sKey);
  },
  "hasOwn": function (oTarget, sKey) {
    return oTarget.hasItem(sKey);
  },
  "defineProperty": function (oTarget, sKey, oDesc) {
    if (oDesc && "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); }
    return oTarget;
  },
  "getPropertyNames": function (oTarget) {
    return Object.getPropertyNames(oTarget).concat(oTarget.keys());
  },
  "getOwnPropertyNames": function (oTarget) {
    return oTarget.keys();
  },
  "getPropertyDescriptor": function (oTarget, sKey) {
    return "not implemented yet!";
  },
  "getOwnPropertyDescriptor": function (oTarget, sKey) {
    return "not implemented yet!";
  },
  "fix":  function (oTarget, sKey) {
    return "not implemented yet!";
  },
});

/* Cookies test */

docCookies.my_cookie = "First value";
alert(docCookies.getItem("my_cookie"));

docCookies.setItem("my_cookie", "Changed value");
alert(docCookies.my_cookie);

See also

Licensing note

Some content (text, examples) in this page has been copied or adapted from the ECMAScript wiki which content is licensed CC 2.0 BY-NC-SA

Revision Source

<p>{{ gecko_minversion_header("18.0") }}</p>
<p>{{ Non-standard_header() }}</p>
<p>{{ warning("The SpiderMonkey Proxy implementation is a prototype and the Proxy API and semantics specifications are unstable. The SpiderMonkey implementation may not reflect the latest specification draft. It is subject to change anytime. It is provided as an experimental feature. Do not rely on it for production code.") }}</p>
<p>{{warning("This page describes the new API (called 'direct_proxies') which is part of Firefox 18. For the previous API (Firefox 17 and below), visit the old proxy API page")}}</p>
<h2 id="Introduction">Introduction</h2>
<p>Proxies are objects for which the programmer has to define the semantics in JavaScript. The default object semantics are implemented in the JavaScript engine, often written in lower-level languages like C++. Proxies let the programmer define most of the behavior of an object in JavaScript. They are said to provide a <strong>meta-programming API</strong>.</p>
<h2 id="Terminology">Terminology</h2>
<dl>
  <dt>
    catch-all mechanism (or "intercession API")</dt>
  <dd>
    The technical term for this feature.</dd>
  <dt>
    proxy</dt>
  <dd>
    The object whose accesses are being intercepted.</dd>
  <dt>
    handler</dt>
  <dd>
    Placeholder object which contains traps.</dd>
  <dt>
    traps</dt>
  <dd>
    The methods that provide property access. This is analogous to the concept of traps in operating systems.</dd>
  <dt>
    target</dt>
  <dd>
    Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants regarding object non-extensibility or non-configurable properties are verified against the target.</dd>
</dl>
<h2 id="Proxy_API">Proxy API</h2>
<p>Proxies are new objects; it's not possible to "proxyfy" an existing object. Here is how to create a proxy</p>
<pre class="brush: js">
var p = new Proxy(target, handler);
</pre>
<p>Where:</p>
<ul>
  <li><code>target</code> is an object (can be any sort of objects, including a native array, a function or even another proxy).</li>
  <li><code>handler</code> is an object whose properties are functions which define the behavior of the proxy when an operation is performed on it.</li>
</ul>
<h2 id="Handler_API">Handler API</h2>
<p>All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.</p>
<table class="standard-table">
  <thead>
    <tr>
      <th>JavaScript code</th>
      <th>Handler method</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>Object.getOwnPropertyDescriptor(proxy, name)</code></td>
      <td><code><strong>getOwnPropertyDescriptor</strong><br />
        function(target, name) -&gt; PropertyDescriptor | undefined</code></td>
      <td>Should return a valid property descriptor object, or <code>undefined</code> to indicate that no property named <code>name</code> exists in the emulated object.</td>
    </tr>
    <tr>
      <td><code>Object.getOwnPropertyNames(proxy)</code></td>
      <td><code><strong>getOwnPropertyNames</strong> function(target) -&gt; [String]</code></td>
      <td>Return an array of all own (non-inherited) property names of the emulated object.</td>
    </tr>
    <tr>
      <td><code>Object.defineProperty(proxy,name,pd)</code></td>
      <td><code><strong>defineProperty</strong> function(target, name, propertyDescriptor) -&gt; any</code></td>
      <td>Define a new property whose attributes are determined by the given <code>propertyDescriptor</code>. The return value of this method is ignored.</td>
    </tr>
    <tr>
      <td><code>delete proxy.name</code></td>
      <td><code><strong>deleteProperty</strong> function(target, name) -&gt; boolean</code></td>
      <td>Delete the named property from the proxy. The boolean return value of this method should indicate whether or not the <code>name</code> property was successfully deleted.</td>
    </tr>
    <tr>
      <td><code>Object.freeze(proxy)</code></td>
      <td><code><strong>freeze</strong> function(target) -&gt; boolean</code></td>
      <td>Freezes the object. The boolean indicates whether the operation was successful</td>
    </tr>
    <tr>
      <td><code>Object.seal(proxy)</code></td>
      <td><code><strong>seal</strong> function(target) -&gt; boolean</code></td>
      <td>Seals the object. The boolean indicates whether the operation was successful</td>
    </tr>
    <tr>
      <td><code>Object.preventExtensions(proxy)</code></td>
      <td><code><strong>preventExtensions</strong> function(target) -&gt; boolean</code></td>
      <td>Makes the object non-extensible. The boolean indicates whether the operation was successful</td>
    </tr>
    <tr>
      <td><code>name in proxy</code></td>
      <td><code><strong>has</strong> function(target, name) -&gt; boolean</code></td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td><code>Object.prototype.hasOwnProperty.call(proxy, name)</code></td>
      <td><code><strong>hasOwn</strong> function(target, name) -&gt; boolean</code></td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>
        <p><code>proxy.name</code> (in the context of "getting the value")</p>
        <p><code>receiver.name</code> (if <code>receiver</code> inherits from a proxy and does not override <code>name</code>)</p>
      </td>
      <td><code><strong>get</strong> function(target, name, receiver) -&gt; any</code></td>
      <td><code>receiver</code> is either the proxy or an object that inherits from the proxy.</td>
    </tr>
    <tr>
      <td>
        <p><code>proxy.name = val</code> (in the context of "setting the value")</p>
        <p><code>receiver.name = val</code> (if <code>receiver</code> inherits from a proxy and does not override <code>name</code>)</p>
      </td>
      <td><code><strong>set</strong> function(target, name, val, receiver) -&gt; boolean</code></td>
      <td><code>receiver</code> is either the proxy or an object that inherits from the proxy.</td>
    </tr>
    <tr>
      <td><code>for(prop in proxy){...}</code></td>
      <td><code><strong>enumerate</strong> function(target) -&gt; [String]</code></td>
      <td>From the proxy user point of view, properties appear in the for..in loop in the same order as they are in the returned array. <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=783829">Known bug</a>: for for..in loops, the iterate trap is called while it should be the enumerate trap</td>
    </tr>
    <tr>
      <td><code>for(prop of proxy){...}</code></td>
      <td><code><strong>iterate</strong> function(target) -&gt; iterator</code></td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td><code>Object.keys(proxy)</code></td>
      <td><code><strong>keys</strong> function(target) -&gt; [String]</code></td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td><code>proxy.apply(thisValue, args)</code></td>
      <td><code><strong>apply</strong> function(target, thisValue, args) -&gt; any</code></td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td><code>new proxy(...args)</code></td>
      <td><code><strong>construct</strong> function(target, args) -&gt; any</code></td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>
<h2 id="Invariants">Invariants</h2>
<p>Even though proxies provide a lot of power to users, some operations are not trapped in order to keep the language consistent:</p>
<ul>
  <li>The double and triple equal (<code>==</code>, <code>===</code>) operator is not trapped. <code>p1 === p2</code> if and only if <code>p1</code> and <code>p2</code> refer to the same proxy.</li>
  <li><code>Object.getPrototypeOf(proxy)</code> unconditionally returns <code>Object.getPrototypeOf(target)</code></li>
  <li><code>typeof proxy</code> unconditionally returns <code>typeof target</code></li>
  <li><code>Object.prototype.toString.call(proxy)</code> unconditionally returns <code>Object.prototype.toString.call(target)</code></li>
</ul>
<h2 id="Examples">Examples</h2>
<h3 id="Very_simple_example">Very simple example</h3>
<p>An object with <code>37</code> as its default value when the property name is not in the object</p>
<pre class="brush: js">
var handler = {
    get: function(target, name){
        return name in target?
            target[name] :
            37;
    }
};

var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;

console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37
</pre>
<h3 id="No-op_forwarding_proxy">No-op forwarding proxy</h3>
<p>In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it.</p>
<pre class="brush: js">
var target = {};
var p = new Proxy(target, {});

p.a = 37; // operation forwarded to the proxy

console.log(target.a); // 37. The operation has been properly forwarded
</pre>
<h3 id="Validation">Validation</h3>
<p>With a <code>Proxy</code>, you can easily validate the passed value for an object.</p>
<pre class="brush: js">
let validator = {
  set: function(obj, prop, value) {
    if (prop === 'age') {
      if (!Number.isInteger(value)) {
        throw new TypeError('The age is not an integer');
      }
      if (value &gt; 200) {
        throw new RangeError('The age seems invalid');
      }
    }

    // The default behavior to store the value
    obj[prop] = value;
  }
};

let person = new Proxy({}, validator);

person.age = 100;
console.log(person.age); // 100
person.age = 'young'; // Throws an exception
person.age = 300; // Throws an exception
</pre>
<h3 id="Manipulating_DOM_nodes">Manipulating DOM nodes</h3>
<p>Sometimes you want to toggle the attribute or class name of two different elements. Here's how:</p>
<pre class="brush: js">
let view = new Proxy({
  selected: null
},
{
  set: function(obj, prop, newval) {
    let oldval = obj[prop];

    if (prop === 'selected') {
      if (oldval) {
        oldval.setAttribute('aria-selected', 'false');
      }
      if (newval) {
        newval.setAttribute('aria-selected', 'true');
      }
    }

    // The default behavior to store the value
    obj[prop] = newval;
  }
});

let i1 = view.selected = document.getElementById('item-1');
console.log(i1.getAttribute('aria-selected')); // 'true'

let i2 = view.selected = document.getElementById('item-2');
console.log(i1.getAttribute('aria-selected')); // 'false'
console.log(i2.getAttribute('aria-selected')); // 'true'
</pre>
<h3 id="Value_correction_and_an_extra_property">Value correction and an extra property</h3>
<p>The <code>products</code> proxy object evaluates the passed value and convert it to an array if needed. The object also supports an extra property called <code>latestBrowser</code> both as a getter and a setter.</p>
<pre class="brush: js">
let products = new Proxy({
  browsers: ['Internet Explorer', 'Netscape']
},
{
  get: function(obj, prop) {
    // An extra property
    if (prop === 'latestBrowser') {
      return obj.browsers[obj.browsers.length - 1];
    }

    // The default behavior to return the value
    return obj[prop];
  },
  set: function(obj, prop, value) {
    // An extra property
    if (prop === 'latestBrowser') {
      obj.browsers.push(value);
      return;
    }

    // Convert the value if it is not an array
    if (typeof value === 'string') {
      value = [value];
    }

    // The default behavior to store the value
    obj[prop] = value;
  }
});

console.log(products.browsers); // ['Internet Explorer', 'Netscape']
products.browsers = 'Firefox'; // pass a string (by mistake)
console.log(products.browsers); // ['Firefox'] &lt;- no problem, the value is an array

products.latestBrowser = 'Chrome';
console.log(products.browsers); // ['Firefox', 'Chrome']
console.log(products.latestBrowser); // 'Chrome'
</pre>
<h3 id="Finding_an_array_item_object_by_its_property">Finding an array item object by its property</h3>
<p>This proxy extends an array with some utility features. As you see, you can flexibly "define" properties without using <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperties"><code>Object.defineProperties</code></a>. This example can be adapted to find a table row by its cell. In that case, the target will be <a href="/en-US/docs/DOM/table.rows"><code>table.rows</code></a>.</p>
<pre class="brush: js">
let products = new Proxy([
  { name: 'Firefox', type: 'browser' },
  { name: 'SeaMonkey', type: 'browser' },
  { name: 'Thunderbird', type: 'mailer' }
],
{
  get: function(obj, prop) {
    // The default behavior to return the value; prop is usually an integer
    if (prop in obj) {
      return obj[prop];
    }

    // Get the number of products; an alias of products.length
    if (prop === 'number') {
      return obj.length;
    }

    let result, types = {};

    for (let product of obj) {
      if (product.name === prop) {
        result = product;
      }
      if (types[product.type]) {
        types[product.type].push(product);
      } else {
        types[product.type] = [product];
      }
    }

    // Get a product by name
    if (result) {
      return result;
    }

    // Get products by type
    if (prop in types) {
      return types[prop];
    }

    // Get product types
    if (prop === 'types') {
      return Object.keys(types);
    }

    return undefined;
  }
});

console.log(products[0]); // { name: 'Firefox', type: 'browser' }
console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' }
console.log(products['Chrome']); // undefined
console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
console.log(products.types); // ['browser', 'mailer']
console.log(products.number); // 3
</pre>
<h3>A complete <code>traps</code> list example</h3>
<p>In order to create a complete sample <code><code>traps</code> list, now we will <em>proxify</em> the </code>docCookies<code> global object of</code> <a href="https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support" title="https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support">the "little framework" published on the <code>document.cookie</code> page</a>.</p>
<pre class="brush: js">
/* get the "docCookies" object here: https://developer.mozilla.org/en-US/docs/DOM/document.cookie */

var docCookies = new Proxy(docCookies, {
&nbsp; "get": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
&nbsp; },
&nbsp; "set": function (oTarget, sKey, vValue) {
&nbsp;&nbsp;&nbsp; if (sKey in oTarget) { return false; }
&nbsp;&nbsp;&nbsp; oTarget.setItem(sKey, vValue.toString());
&nbsp;&nbsp;&nbsp; return true;
&nbsp; },
&nbsp; "delete": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; if (sKey in oTarget) { return false; }
&nbsp;&nbsp;&nbsp; oTarget.removeItem(sKey);
&nbsp;&nbsp;&nbsp; return true;
&nbsp; },
&nbsp; "enumerate": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return oTarget.keys();
&nbsp; },
&nbsp; "iterate": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return oTarget.keys();
&nbsp; },
&nbsp; "keys": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return oTarget.keys();
&nbsp; },
&nbsp; "has": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return sKey in oTarget || oTarget.hasItem(sKey);
&nbsp; },
&nbsp; "hasOwn": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return oTarget.hasItem(sKey);
&nbsp; },
&nbsp; "defineProperty": function (oTarget, sKey, oDesc) {
&nbsp;&nbsp;&nbsp; if (oDesc &amp;&amp; "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); }
&nbsp;&nbsp;&nbsp; return oTarget;
&nbsp; },
&nbsp; "getPropertyNames": function (oTarget) {
&nbsp;&nbsp;&nbsp; return Object.getPropertyNames(oTarget).concat(oTarget.keys());
&nbsp; },
&nbsp; "getOwnPropertyNames": function (oTarget) {
&nbsp;&nbsp;&nbsp; return oTarget.keys();
&nbsp; },
&nbsp; "getPropertyDescriptor": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return "not implemented yet!";
&nbsp; },
&nbsp; "getOwnPropertyDescriptor": function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return "not implemented yet!";
&nbsp; },
&nbsp; "fix":&nbsp; function (oTarget, sKey) {
&nbsp;&nbsp;&nbsp; return "not implemented yet!";
&nbsp; },
});

/* Cookies test */

docCookies.my_cookie = "First value";
alert(docCookies.getItem("my_cookie"));

docCookies.setItem("my_cookie", "Changed value");
alert(docCookies.my_cookie);</pre>
<h2 id="See_also">See also</h2>
<ul>
  <li><a class="external" href="http://jsconf.eu/2010/speaker/be_proxy_objects.html">"Proxies are awesome" Brendan Eich presentation at JSConf</a> (<a class="external" href="http://www.slideshare.net/BrendanEich/metaprog-5303821">slides</a>)</li>
  <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">ECMAScript Harmony Proxy proposal page</a> and <a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies_semantics">ECMAScript Harmony proxy semantics page</a></li>
  <li><a class="external" href="http://soft.vub.ac.be/~tvcutsem/proxies/">Tutorial on proxies</a></li>
  <li><a href="/en-US/docs/JavaScript/Old_Proxy_API" title="/en-US/docs/JavaScript/Old_Proxy_API">Old Proxy API page</a></li>
  <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/watch"><code>Object.watch</code></a> is a non-standard feature but has been suppoted in Gecko for a long time.</li>
</ul>
<h2 id="Licensing_note">Licensing note</h2>
<p>Some content (text, examples) in this page has been copied or adapted from the <a class="external" href="http://wiki.ecmascript.org/doku.php">ECMAScript wiki</a> which content is licensed <a class="external" href="http://creativecommons.org/licenses/by-nc-sa/2.0/">CC 2.0 BY-NC-SA</a></p>
Revert to this revision