首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Proxy.handler.get

handler.get()?方法用于拦截对象的读取属性操作。

语法

代码语言:javascript
复制
var p = new Proxy(target, {
  get: function(target, property, receiver) {
  }
});

参数

以下是传递给get方法的参数,this上下文绑定在handler对象上.

target目标对象。

property被获取的属性名。

receiverProxy或者继承Proxy的对象

返回值

get方法可以返回任何值。

描述

handler.get?方法用于拦截对象的读取属性操作。

拦截

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

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

约束

如果违背了以下的约束,proxy会抛出?TypeError:

  • 如果要访问的目标属性是不可写以及不可配置的,则返回的值必须与该目标属性的值相同。

  • 如果要访问的目标属性没有配置访问方法,即get方法是undefined的,则返回值必须为undefined。

示例

以下代码演示如何拦截属性值的读取操作。

代码语言:javascript
复制
var p = new Proxy({}, {
  get: function(target, prop, receiver) {
    console.log('called: ' + prop);
    return 10;
  }
});

console.log(p.a); // "called: a"
                  // 10

以下代码演示违反约束的情况。

代码语言:javascript
复制
var obj = {};
Object.defineProperty(obj, 'a', { 
  configurable: false, 
  enumerable: false, 
  value: 10, 
  writable: false 
});

var p = new Proxy(obj, {
  get: function(target, prop) {
    return 20;
  }
});

p.a; // TypeError is thrown

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of '[Get]' in that specification.

Standard

Initial definition.

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

Living Standard

?

浏览器兼容性

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)

?

?

?

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com