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

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

修订内容

{{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

Proxy(代理)对象定义一个target和一个handle,handle实现了一个get捕捉方法。通过这个方法,被代理的对象对于未定义的属性,不再返回undefined,而是返回一个42的数字。

更多例子参见 {{jsxref("Proxy")}} 引用页

术语

在讨论代理{{jsxref("Proxy")}}的功能时,以下这些术语将会被使用到。T

{{jsxref("Global_Objects/Proxy/handler","handler","","true")}}
Placeholder object which contains traps.
traps
该方法提供属性访问. 和操作系统中的traps的概念类似.
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(常量)
语义上,当实现固定的操作而不发生改变的量叫做不变量(常量)。如果你违反了管理者制定的常量,将会抛出一个{{jsxref("TypeError")}}这样的错误。

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

{{jsxref("Proxy.revocable()")}}方法被用来创建可撤销的代理对象。这意味着代理可以通过撤销函数来撤销并且关掉代理。后来,代理上的任意的操作都会导致{{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")}} 式一个可提供JavaScript操作判断的内建对象。该方法和 代理句柄(proxy handlers)类似,但需要注意的是Reflect方法并不是一个函数对象。

反射帮助实现从处理器到目标的默认转发操作, 但是Reflect方法还没有在Firefox浏览器中实现

使用{{jsxref("Reflect.has()")}}举例, 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>Proxy(代理)对象定义一个target和一个handle,handle实现了一个get捕捉方法。通过这个方法,被代理的对象对于未定义的属性,不再返回undefined,而是返回一个42的数字。</p>

<div class="note">
<p>更多例子参见 {{jsxref("Proxy")}} 引用页</p>
</div>

<h3 id="术语">术语</h3>

<p>在讨论代理{{jsxref("Proxy")}}的功能时,以下这些术语将会被使用到。T</p>

<dl>
 <dt>{{jsxref("Global_Objects/Proxy/handler","handler","","true")}}</dt>
 <dd>Placeholder object which contains traps.</dd>
 <dt>traps</dt>
 <dd>该方法提供属性访问. 和操作系统中的traps的概念类似.</dd>
 <dt>target(目标)</dt>
 <dd>生成代理虚拟化的对象。它经常被作为代理的后端存储使用。</dd>
 <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>语义上,当实现固定的操作而不发生改变的量叫做不变量(常量)。如果你违反了管理者制定的常量,将会抛出一个{{jsxref("TypeError")}}这样的错误。</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>{{jsxref("Proxy.revocable()")}}方法被用来创建可撤销的代理对象。这意味着代理可以通过撤销函数来撤销并且关掉代理。后来,代理上的任意的操作都会导致{{jsxref("TypeError")}}.</p>

<p>&nbsp;</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")}} 式一个可提供JavaScript操作判断的内建对象。该方法和&nbsp;<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">代理句柄(proxy handlers)</a>类似,但需要注意的是Reflect方法并不是一个函数对象。</p>

<p>反射帮助实现从处理器到目标的默认转发操作,&nbsp;但是Reflect方法还没有在Firefox浏览器中实现</p>

<p>使用{{jsxref("Reflect.has()")}}举例, 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>
恢复到这个版本