Apply your JS skills to key Mozilla projects as an MDN Fellow!




    该特性目前仍处于 ECMAScript 6 规范草案中


    The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).


    Placeholder object which contains traps.
    The methods that provide property access. This is analogous to the concept of traps in operating systems.
    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.


    var p = new Proxy(target, handler);




    Creates a revocable Proxy object.

    Methods of the handler object

    The handler object is a placeholder object which contains traps for Proxy.

    一共有 14 种可代理操作,每种操作的代号(属性名/方法名)和触发这种操作的方式列举如下。注意,如果没有定义某种操作,那么这种操作会被转发到目标对象身上。

    在读取代理对象的原型时触发该操作,比如在执行 Object.getPrototypeOf(proxy) 时。
    在设置代理对象的原型时触发该操作,比如在执行 Object.setPrototypeOf(proxy, null) 时。
    在判断一个代理对象是否是可扩展时触发该操作,比如在执行 Object.isExtensible(proxy) 时。
    在让一个代理对象不可扩展时触发该操作,比如在执行 Object.preventExtensions(proxy) 时。
    在获取代理对象某个属性的属性描述时触发该操作,比如在执行 Object.getOwnPropertyDescriptor(proxy, "foo") 时。
    在定义代理对象某个属性时的属性描述时触发该操作,比如在执行 Object.defineProperty(proxy, "foo", {}) 时。
    在判断代理对象是否拥有某个属性时触发该操作,比如在执行 "foo" in proxy 时。
    在读取代理对象的某个属性时触发该操作,比如在执行 时。
    在给代理对象的某个属性赋值时触发该操作,比如在执行 = 1 时。
    在删除代理对象的某个属性时触发该操作,比如在执行 delete 时。
    在遍历代理对象的属性时触发该操作,比如在执行 for(i in proxy){} 时。
    在获取代理对象的所有属性键时触发该操作,比如在执行 Object.getOwnPropertyNames(proxy) 时。
    在调用一个目标对象为函数的代理对象时触发该操作,比如在执行 proxy() 时。
    在给一个目标对象为构造函数的代理对象构造实例时触发该操作,比如在执行new proxy() 时。


    Basic example

    In this simple example the number 37 gets returned as the default value when the property name is not in the object. It is using the get handler.

    var handler = {
        get: function(target, name){
            return name in target?
                target[name] :
    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


    With a Proxy, you can easily validate the passed value for an object. This example uses the set handler.

    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

    Extending constructor

    A function proxy could easily extend a constructor with a new constructor. This example uses the construct and apply handlers.

    function extend(sup,base) {
      var descriptor = Object.getOwnPropertyDescriptor(
      base.prototype = Object.create(sup.prototype);
      var handler = {
        construct: function(target, args) {
          var obj = Object.create(base.prototype);
          return obj;
        apply: function(target, that, args) {
      var proxy = new Proxy(base,handler);
      descriptor.value = proxy;
      Object.defineProperty(base.prototype, "constructor", descriptor);
      return proxy;
    var Person = function(name){ = name
    var Boy = extend(Person, function(name, age) {
      this.age = age;
    }); = "M";
    var Peter = new Boy("Peter", 13);
    console.log(;  // "M"
    console.log(; // "Peter"
    console.log(Peter.age);  // 13

    Manipulating DOM nodes

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

    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') {
        // 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 ( === prop) {
            result = product;
          if (types[product.type]) {
          } 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

    Now in order to create a complete sample traps list, for didactic purposes, we will try to proxify a non native object that is particularly suited to this type of operation: the docCookies global object created by the "little framework" published on the document.cookie page.

      var docCookies = ... get the "docCookies" object here:
    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; }
        return oTarget.setItem(sKey, vValue);
      "deleteProperty": function (oTarget, sKey) {
        if (sKey in oTarget) { return false; }
        return oTarget.removeItem(sKey);
      "enumerate": function (oTarget, sKey) {
        return oTarget.keys();
      "ownKeys": function (oTarget, sKey) {
        return oTarget.keys();
      "has": function (oTarget, sKey) {
        return sKey in oTarget || oTarget.hasItem(sKey);
      "defineProperty": function (oTarget, sKey, oDesc) {
        if (oDesc && "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); }
        return oTarget;
      "getOwnPropertyDescriptor": function (oTarget, sKey) {
        var vValue = oTarget.getItem(sKey);
        return vValue ? {
          "value": vValue,
          "writable": true,
          "enumerable": true,
          "configurable": false
        } : undefined;
    /* Cookies test */
    alert(docCookies.my_cookie1 = "First value");
    docCookies.setItem("my_cookie1", "Changed value");

    Browser compatibility

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support


    18 (18) 12 ? ?
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support ? ? 18 (18) ? ? ?

    Gecko specific notes

    • At present, Object.getPrototypeOf(proxy) unconditionally returns Object.getPrototypeOf(target), because the ES6 getPrototypeOf trap is not yet implemented (bug 888969, bug 888969).
    • Array.isArray(proxy) unconditionally returns Array.isArray(target) (bug 1111785, bug 1111785).
    • unconditionally returns, because ES6 Symbol.toStringTag is not yet implemented (bug 1114580).

    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.


    此页面的贡献者有: ziyunfei, teoli
    最后编辑者: ziyunfei,