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 976167 of Meta programming

  • 版本网址缩略名: Web/JavaScript/Guide/Meta_programming
  • 版本标题: Meta programming
  • 版本 id: 976167
  • 创建于:
  • 创建者: binhex
  • 是否是当前版本?
  • 评论

修订内容

{{jsSidebar("JavaScript Guide")}} {{Previous("Web/JavaScript/Guide/Iterators_and_Generators")}}

从ECMAScript6开始,JavaScript添加了{{jsxref("Proxy")}}和 {{jsxref("Reflect")}}对象,允许你解释和定义客制化基础语言操作行为(比如,属性查找,赋值,枚举,函数调用,等等)。通过这两个对象,你可以在JavaScript元级别(meta level)编程。

代理(Proxies)

从ECMAScript6开始引进,{{jsxref("Proxy")}}对象允许你解释特定操作和实现客制化行为。例如得到一个对象的属性:

var handler = {
  get: function(target, name){
    return name in target ? target[name] : 42;
}};
var p = new Proxy({}, handler);
p.a = 1;
console.log(p.a, p.b); // 1, 42

The Proxy object defines a target (an object here) and a handler object in which a get trap is implemented. Here, an object that is proxied will not return undefined when getting undefined properties, but will instead return the number 42.

Additional examples are available on the {{jsxref("Proxy")}} reference page.

Terminology

The following terms are used when talking about the functionality of proxies.

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 (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.
invariants
Semantics that remain unchanged when implementing custom operations are called invariants. If you violate the invariants of a handler, a {{jsxref("TypeError")}} will be thrown.

Handlers and traps

The following table summarizes the available traps available to Proxy objects. See the reference pages for detailed explanations and examples.

Handler / trap Interceptions Invariants
{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}} {{jsxref("Object.getPrototypeOf()")}}
{{jsxref("Reflect.getPrototypeOf()")}}
{{jsxref("Object/proto", "__proto__")}}
{{jsxref("Object.prototype.isPrototypeOf()")}}
{{jsxref("Operators/instanceof", "instanceof")}}
getPrototypeOf method must return an object or null.

If target is not extensible, Object.getPrototypeOf(proxy) method must return the same value as Object.getPrototypeOf(target).
{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}} {{jsxref("Object.setPrototypeOf()")}}
{{jsxref("Reflect.setPrototypeOf()")}}

If target is not extensible, the prototype parameter must be the same value as Object.getPrototypeOf(target).

{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}

{{jsxref("Object.isExtensible()")}}

{{jsxref("Reflect.isExtensible()")}}

Object.isExtensible(proxy) must return the same value as Object.isExtensible(target).

{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}

{{jsxref("Object.preventExtensions()")}}

{{jsxref("Reflect.preventExtensions()")}}

Object.preventExtensions(proxy) only returns true if Object.isExtensible(proxy) is false.

{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}

{{jsxref("Object.getOwnPropertyDescriptor()")}}

{{jsxref("Reflect.getOwnPropertyDescriptor()")}}

getOwnPropertyDescriptor must return an object or undefined.

A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.

A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.

A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible.

A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.

The result of Object.getOwnPropertyDescriptor(target) can be applied to the target object using Object.defineProperty and will not throw an exception.

{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}

{{jsxref("Object.defineProperty()")}}

{{jsxref("Reflect.defineProperty()")}}

A property cannot be added, if the target object is not extensible.

A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object.

A property may not be non-configurable, if a corresponding configurable property of the target object exists.

If a property has a corresponding target object property then Object.defineProperty(target, prop, descriptor) will not throw an exception.

In strict mode, a false return value from the defineProperty handler will throw a {{jsxref("TypeError")}} exception.

{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}

Property query: foo in proxy

Inherited property query: foo in Object.create(proxy)

{{jsxref("Reflect.has()")}}

A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.

A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.

{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}

Property access: proxy[foo]and proxy.bar

Inherited property access: Object.create(proxy)[foo]

{{jsxref("Reflect.get()")}}

The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable data property.

The value reported for a property must be undefined if the corresponding target object property is non-configurable accessor property that has undefined as its [[Get]] attribute.

{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}

Property assignment: proxy[foo] = bar and proxy.foo = bar

Inherited property assignment: Object.create(proxy)[foo] = bar

{{jsxref("Reflect.set()")}}

Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.

Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has undefined as its [[Set]] attribute.

In strict mode, a false return value from the set handler will throw a {{jsxref("TypeError")}} exception.

{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}

Property deletion: delete proxy[foo] and delete proxy.foo

{{jsxref("Reflect.deleteProperty()")}}

A property cannot be deleted, if it exists as a non-configurable own property of the target object.
{{jsxref("Global_Objects/Proxy/handler/enumerate", "handler.enumerate()")}}

Property enumeration / for...in: for (var name in proxy) {...}

{{jsxref("Reflect.enumerate()")}}

The enumerate method must return an object.
{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}

{{jsxref("Object.getOwnPropertyNames()")}}
{{jsxref("Object.getOwnPropertySymbols()")}}
{{jsxref("Object.keys()")}}
{{jsxref("Reflect.ownKeys()")}}

The result of ownKeys is a List.

The Type of each result List element is either {{jsxref("String")}} or {{jsxref("Symbol")}}.

The result List must contain the keys of all non-configurable own properties of the target object.

If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values.

{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}

proxy(..args)

{{jsxref("Function.prototype.apply()")}} and {{jsxref("Function.prototype.call()")}}

{{jsxref("Reflect.apply()")}}

There are no invariants for the handler.apply method.
{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}

new proxy(...args)
{{jsxref("Reflect.construct()")}}

The result must be an Object.

Revocable Proxy

The {{jsxref("Proxy.revocable()")}} method is used to create a revocable Proxy object. This means that the proxy can be revoked via the function revoke and switches the proxy off. Afterwards, any operation leads on the proxy leads to a {{jsxref("TypeError")}}.

var revocable = Proxy.revocable({}, {
  get: function(target, name) {
    return "[[" + name + "]]";
  }
});
var proxy = revocable.proxy;
console.log(proxy.foo); // "[[foo]]"

revocable.revoke();

console.log(proxy.foo); // TypeError is thrown
proxy.foo = 1           // TypeError again
delete proxy.foo;       // still TypeError
typeof proxy            // "object", typeof doesn't trigger any trap

Reflection

{{jsxref("Reflect")}} is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the proxy handlers. Reflect It is not a function object.

Reflect helps with forwarding default operations from the handler to the target. Note that Reflect is not implemented in Firefox yet.

With {{jsxref("Reflect.has()")}} for example, you get the in operator as a function:

Reflect.has(Object, "assign"); // true

{{Previous("Web/JavaScript/Guide/Iterators_and_Generators")}}

修订版来源

<div>{{jsSidebar("JavaScript Guide")}} {{Previous("Web/JavaScript/Guide/Iterators_and_Generators")}}</div>

<p class="summary">从ECMAScript6开始,JavaScript添加了{{jsxref("Proxy")}}和 {{jsxref("Reflect")}}对象,允许你解释和定义客制化基础语言操作行为(比如,属性查找,赋值,枚举,函数调用,等等)。通过这两个对象,你可以在JavaScript元级别(meta level)编程。</p>

<h2 id="Proxies">代理(Proxies)</h2>

<p>从ECMAScript6开始引进,{{jsxref("Proxy")}}对象允许你解释特定操作和实现客制化行为。例如得到一个对象的属性:</p>

<pre class="brush: js">
var handler = {
  get: function(target, name){
    return name in target ? target[name] : 42;
}};
var p = new Proxy({}, handler);
p.a = 1;
console.log(p.a, p.b); // 1, 42
</pre>

<p>The <code>Proxy</code> object defines a <em>target</em> (an object here) and a <em>handler</em> object in which a <code>get</code> <em>trap</em> is implemented. Here, an object that is proxied will not return <code>undefined</code> when getting undefined properties, but will instead return the number 42.</p>

<div class="note">
<p>Additional examples are available on the {{jsxref("Proxy")}} reference page.</p>
</div>

<h3 id="Terminology">Terminology</h3>

<p>The following terms are used when talking about the functionality of proxies.</p>

<dl>
 <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">handler</a></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 (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.</dd>
 <dt>invariants</dt>
 <dd>Semantics that remain unchanged when implementing custom operations are called <em>invariants</em>. If you violate the invariants of a handler, a {{jsxref("TypeError")}} will be thrown.</dd>
</dl>

<h2 id="Handlers_and_traps">Handlers and traps</h2>

<p>The following table summarizes the available traps available to <code>Proxy</code> objects. See the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">reference pages</a> for detailed explanations and examples.</p>

<table class="standard-table">
 <thead>
  <tr>
   <th>Handler / trap</th>
   <th>Interceptions</th>
   <th>Invariants</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}</td>
   <td>{{jsxref("Object.getPrototypeOf()")}}<br />
    {{jsxref("Reflect.getPrototypeOf()")}}<br />
    {{jsxref("Object/proto", "__proto__")}}<br />
    {{jsxref("Object.prototype.isPrototypeOf()")}}<br />
    {{jsxref("Operators/instanceof", "instanceof")}}</td>
   <td><code>getPrototypeOf</code> method must return an object or <code>null</code>.<br />
    <br />
    If <code>target</code> is not extensible, <code>Object.getPrototypeOf(proxy)</code> method must return the same value as <code>Object.getPrototypeOf(target)</code>.</td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}</td>
   <td>{{jsxref("Object.setPrototypeOf()")}}<br />
    {{jsxref("Reflect.setPrototypeOf()")}}</td>
   <td>
    <p>If <code>target</code> is not extensible, the <code>prototype</code> parameter must be the same value as <code>Object.getPrototypeOf(target)</code>.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}</td>
   <td>
    <p>{{jsxref("Object.isExtensible()")}}</p>

    <p>{{jsxref("Reflect.isExtensible()")}}</p>
   </td>
   <td>
    <p><code>Object.isExtensible(proxy)</code> must return the same value as <code>Object.isExtensible(target)</code>.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}</td>
   <td>
    <p>{{jsxref("Object.preventExtensions()")}}</p>

    <p>{{jsxref("Reflect.preventExtensions()")}}</p>
   </td>
   <td>
    <p><code>Object.preventExtensions(proxy)</code> only returns <code>true</code> if <code>Object.isExtensible(proxy)</code> is <code>false</code>.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}</td>
   <td>
    <p>{{jsxref("Object.getOwnPropertyDescriptor()")}}</p>

    <p>{{jsxref("Reflect.getOwnPropertyDescriptor()")}}</p>
   </td>
   <td>
    <p><code>getOwnPropertyDescriptor</code> must return an object or <code>undefined</code>.</p>

    <p>A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.</p>

    <p>A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.</p>

    <p>A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible.</p>

    <p>A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.</p>

    <p>The result of <code>Object.getOwnPropertyDescriptor(target)</code> can be applied to the target object using <code>Object.defineProperty</code> and will not throw an exception.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}</td>
   <td>
    <p>{{jsxref("Object.defineProperty()")}}</p>

    <p>{{jsxref("Reflect.defineProperty()")}}</p>
   </td>
   <td>
    <p>A property cannot be added, if the target object is not extensible.</p>

    <p>A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object.</p>

    <p>A property may not be non-configurable, if a corresponding configurable property of the target object exists.</p>

    <p>If a property has a corresponding target object property then <code>Object.defineProperty(target, prop, descriptor)</code> will not throw an exception.</p>

    <p>In strict mode, a <code>false</code> return value from the <code>defineProperty</code> handler will throw a {{jsxref("TypeError")}} exception.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}</td>
   <td>
    <p>Property query: <code>foo in proxy</code></p>

    <p>Inherited property query: <code>foo in Object.create(proxy)</code></p>

    <p>{{jsxref("Reflect.has()")}}</p>
   </td>
   <td>
    <p>A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.</p>

    <p>A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}</td>
   <td>
    <p>Property access: <code>proxy[foo]</code>and <code>proxy.bar</code></p>

    <p>Inherited property access: <code>Object.create(proxy)[foo]</code></p>

    <p>{{jsxref("Reflect.get()")}}</p>
   </td>
   <td>
    <p>The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable data property.</p>

    <p>The value reported for a property must be undefined if the corresponding target object property is non-configurable accessor property that has undefined as its [[Get]] attribute.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}</td>
   <td>
    <p>Property assignment: <code>proxy[foo] = bar</code> and <code>proxy.foo = bar</code><br />
     <br />
     Inherited property assignment: <code>Object.create(proxy)[foo] = bar</code><br />
     <br />
     {{jsxref("Reflect.set()")}}</p>
   </td>
   <td>
    <p>Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.</p>

    <p>Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has <code>undefined</code> as its [[Set]] attribute.</p>

    <p>In strict mode, a <code>false</code> return value from the <code>set</code> handler will throw a {{jsxref("TypeError")}} exception.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}</td>
   <td>
    <p>Property deletion: <code>delete proxy[foo]</code> and <code>delete proxy.foo</code><br />
     <br />
     {{jsxref("Reflect.deleteProperty()")}}</p>
   </td>
   <td>A property cannot be deleted, if it exists as a non-configurable own property of the target object.</td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/enumerate", "handler.enumerate()")}}</td>
   <td>
    <p>Property enumeration / for...in: <code>for (var name in proxy) {...}</code><br />
     <br />
     {{jsxref("Reflect.enumerate()")}}</p>
   </td>
   <td>The <code>enumerate</code> method must return an object.</td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}</td>
   <td>
    <p>{{jsxref("Object.getOwnPropertyNames()")}}<br />
     {{jsxref("Object.getOwnPropertySymbols()")}}<br />
     {{jsxref("Object.keys()")}}<br />
     {{jsxref("Reflect.ownKeys()")}}</p>
   </td>
   <td>
    <p>The result of <code>ownKeys</code> is a List.<br />
     <br />
     The Type of each result List element is either {{jsxref("String")}} or {{jsxref("Symbol")}}.<br />
     <br />
     The result List must contain the keys of all non-configurable own properties of the target object.<br />
     <br />
     If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}</td>
   <td>
    <p><code>proxy(..args)</code><br />
     <br />
     {{jsxref("Function.prototype.apply()")}} and {{jsxref("Function.prototype.call()")}}<br />
     <br />
     {{jsxref("Reflect.apply()")}}</p>
   </td>
   <td>There are no invariants for the <code>handler.apply</code> method.</td>
  </tr>
  <tr>
   <td>{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}</td>
   <td>
    <p><code>new proxy(...args)</code><br />
     {{jsxref("Reflect.construct()")}}</p>
   </td>
   <td>
    <p>The result must be an <code>Object</code>.</p>
   </td>
  </tr>
 </tbody>
</table>

<h2 id="Revocable_Proxy">Revocable <code>Proxy</code></h2>

<p>The {{jsxref("Proxy.revocable()")}} method is used to create a revocable <code>Proxy</code> object. This means that the proxy can be revoked via the function <code>revoke</code> and switches the proxy off. Afterwards, any operation leads on the proxy leads to a {{jsxref("TypeError")}}.</p>

<pre class="brush: js">
var revocable = Proxy.revocable({}, {
  get: function(target, name) {
    return "[[" + name + "]]";
  }
});
var proxy = revocable.proxy;
console.log(proxy.foo); // "[[foo]]"

revocable.revoke();

console.log(proxy.foo); // TypeError is thrown
proxy.foo = 1           // TypeError again
delete proxy.foo;       // still TypeError
typeof proxy            // "object", typeof doesn't trigger any trap</pre>

<h2 id="Reflection">Reflection</h2>

<p>{{jsxref("Reflect")}} is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">proxy handlers</a>. <code>Reflect</code> It is not a function object.</p>

<p><code>Reflect</code> helps with forwarding default operations from the handler to the target. Note that <code>Reflect</code> is not implemented in Firefox yet.</p>

<p>With {{jsxref("Reflect.has()")}} for example, you get the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> operator</a> as a function:</p>

<pre class="brush: js">
Reflect.has(Object, "assign"); // true
</pre>

<p>{{Previous("Web/JavaScript/Guide/Iterators_and_Generators")}}</p>
恢复到这个版本