handler.defineProperty() 用于拦截对对象的 Object.defineProperty() 操作。

语法

var p = new Proxy(target, {
  defineProperty: function(target, property, descriptor) {
  }
});

参数

下列参数将会被传递给 defineProperty 方法。 this 绑定在 handler 对象上。

target
目标对象。
property
待检索其描述的属性名。
descriptor
待定义或修改的属性的描述符。

返回值

defineProperty 方法必须以一个 Boolean 返回,表示定义该属性的操作成功与否。

描述

handler.defineProperty() 用于拦截对对象的 Object.defineProperty() 操作。

拦截

该方法会拦截目标对象的以下操作 :

不变量

如果违背了以下的不变量,proxy会抛出 TypeError:

示例

以下代码演示如何拦截对目标对象的 Object.defineProperty() 操作。

var p = new Proxy({}, {
  defineProperty: function(target, prop, descriptor) {
    console.log('called: ' + prop);
    return true;
  }
});

var desc = { configurable: true, enumerable: true, value: 10 };
Object.defineProperty(p, 'a', desc); // "called: a"

当调用 Object.defineProperty() 或者 Reflect.defineProperty(),传递给 definePropertydescriptor   有一个限制 - 只有以下属性才有用,非标准的属性将会被无视 :

var p = new Proxy({}, {
  defineProperty(target, prop, descriptor) {
    console.log(descriptor);
    return Reflect.defineProperty(target, prop, descriptor);
  }
});

Object.defineProperty(p, 'name', {
  value: 'proxy',
  type: 'custom'
});  // { value: 'proxy' }

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
[[DefineOwnProperty]]
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
[[DefineOwnProperty]]
Draft  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support ? 18 (18) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 18.0 (18) ? ? ?

另见