handler.get() method is a trap for getting a property value.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

句法

const p = new Proxy(target, {
  get: function(target, property, receiver) {
  }
});
					

参数

The following parameters are passed to the get() 方法。 this is bound to the handler.

target

The target object.

property
The name or Symbol of the property to get.
receiver

Either the proxy or an object that inherits from the proxy.

返回值

get() method can return any value.

描述

handler.get() method is a trap for getting a property value.

Interceptions

This trap can intercept these operations:

  • Property access: proxy [ foo ] and proxy . bar
  • Inherited property access: Object.create( proxy )[ foo ]
  • Reflect.get()

Invariants

If the following invariants are violated, the proxy will throw a TypeError :

  • 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 own data property.
  • The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has undefined as its [[Get]] 属性。

范例

Trap for getting a property value

The following code traps getting a property value.

const p = new Proxy({}, {
  get: function(target, property, receiver) {
    console.log('called: ' + property);
    return 10;
  }
});
console.log(p.a); // "called: a"
                  // 10
					

The following code violates an invariant.

const obj = {};
Object.defineProperty(obj, 'a', {
  configurable: false,
  enumerable: false,
  value: 10,
  writable: false
});
const p = new Proxy(obj, {
  get: function(target, property) {
    return 20;
  }
});
p.a; // TypeError is thrown
					

规范

规范
ECMAScript (ECMA-262)
The definition of '[[Get]]' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
get Chrome 49 Edge 12 Firefox 18 IE No Opera 36 Safari 10 WebView Android 49 Chrome Android 49 Firefox Android 18 Opera Android 36 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: