当前位置:网站首页>ES6 Proxy和Object.defineProperty
ES6 Proxy和Object.defineProperty
2022-04-22 17:08:00 【shaobohong】
Object.defindProperty
缺陷:
- 无法监听数组变化
- 只能劫持对象的属性
var obj = {name: 'name'}
Object.defineProperty(obj, 'name', {
get: function(){
return '123';
}
})
obj.name // 123
Proxy
基础用法:
new Proxy(target, handler);
targer 要拦截的对象,handler 拦截行为对象
var obj = new Proxy({}, {
get: function(){
return '35';
}
})
obj.name;// 35
obj.age;// 35
obj2 = {}
obj2.name;// 无
obj2.age;// 无
Proxy针对的是对象实例obj,而不是上面代码中的空对象{}
get(target, propKey[, proxy])
用于拦截某个属性的读取操作,接受三个参数,target为目标对象,propKey为属性名,proxy为实例本身(严格地说,是操作行为所针对的对象),其中最后一个参数可选。
var obj = new Proxy({}, {
get: function(target, propKey, proxy){
console.dir(target); // Object
console.dir(propkey); // name、age
console.dir(proxy); // Proxy
if (propKey in target) {
return target[propKey];
} else {
console.log('没有这个属性');
return null;
}
}
})
obj.name = 'new name';
obj.name;// new name
obj.age;// null
var obj = new Proxy({}, {
get: function(target, propKey, proxy){
return proxy;
}
})
console.log(obj.a === obj)// true
set(target, propKey, propValue[, proxy])
用来拦截某个属性的赋值操作,可以接受四个参数,依次为目标对象、属性名、属性值和 Proxy 实例本身,其中最后一个参数可选
var obj = new Proxy({}, {
set: function(target, key, val, proxy){
console.log(key)
if (key == 'name') {
console.log('name 不可修改')
} else {
target[key] = val;
}
}
})
obj.name = 'new name';// undefined
obj.age = '99';// 99
Proxy可以拦截的其他方法:
- has(target, propKey):拦截
propKey in proxy的操作,返回一个布尔值。 - deleteProperty(target, propKey):拦截
delete proxy[propKey]的操作,返回一个布尔值。 - ownKeys(target):拦截
Object.getOwnPropertyNames(proxy)、Object.getOwnPropertySymbols(proxy)、Object.keys(proxy)、for...in循环,返回一个数组。该方法返回目标对象所有自身的属性的属性名,而Object.keys()的返回结果仅包括目标对象自身的可遍历属性。 - getOwnPropertyDescriptor(target, propKey):拦截
Object.getOwnPropertyDescriptor(proxy, propKey),返回属性的描述对象。 - defineProperty(target, propKey, propDesc):拦截
Object.defineProperty(proxy, propKey, propDesc)、Object.defineProperties(proxy, propDescs),返回一个布尔值。 - preventExtensions(target):拦截
Object.preventExtensions(proxy),返回一个布尔值。 - getPrototypeOf(target):拦截
Object.getPrototypeOf(proxy),返回一个对象。 - isExtensible(target):拦截
Object.isExtensible(proxy),返回一个布尔值。 - setPrototypeOf(target, proto):拦截
Object.setPrototypeOf(proxy, proto),返回一个布尔值。如果目标对象是函数,那么还有两种额外操作可以拦截。 - apply(target, object, args):拦截 Proxy 实例作为函数调用的操作,比如
proxy(...args)、proxy.call(object, ...args)、proxy.apply(...)。 - construct(target, args):拦截 Proxy 实例作为构造函数调用的操作,比如
new proxy(...args)。
Proxy.revocable()
let {proxy, revoke} = Proxy.revocable({}, {});
proxy.foo = 123;
proxy.foo // 123
revoke();
proxy.foo // 报错
console.dir(Proxy.revocable({}, {})); //Object {proxy, revoke}
返回一个可以取消的Proxy实例

this问题
在 Proxy 代理的情况下,目标对象内部的this关键字会指向 Proxy 代理。
const target = {
m: function () {
console.log(this === proxy);
}
};
const handler = {};
const proxy = new Proxy(target, handler);
target.m() // false
proxy.m() // true
const target = new Date();
const handler = {};
const proxy = new Proxy(target, handler);
proxy.getDate();
// TypeError: this is not a Date object.
const target = new Date('2015-01-01');
const handler = {
get(target, prop) {
if (prop === 'getDate') {
return target.getDate.bind(target);
}
return Reflect.get(target, prop);
}
};
const proxy = new Proxy(target, handler);
proxy.getDate() // 1
版权声明
本文为[shaobohong]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_17613195/article/details/106502251
边栏推荐
- Bisect -- insert new data into the list and keep it in order
- Concept and application of logarithm
- Shiro缓存管理
- Design from 0_ Rc522 read / write card based on stm32f1
- Cognitive series 4: Notes on cognitive breakthrough
- RT thread studio workspace encoding is set to UTF-8
- 全网征集!说说你跟宜搭之间的故事吧
- Practice questions and answers of evaluation technical methods in 2022 environmental impact assessment engineer examination
- [句型] 二十四、特殊疑问句
- Hybrid Backpack
猜你喜欢

从0开始设计_基于STM32F1的RC522读写卡

Cognitive series 4: Notes on cognitive breakthrough

Redis(16) -- Redis集群

Vscode most complete practical plug-in (VIP collection version)

Globalmapper20 how to batch convert SHP to KML and bring attributes

SDN学习之Opendaylight浅析(五)

2022年环境影响评价工程师考试案例分析练习题及答案

2022年湖南省初级会计职称考试经济法基础练习题及答案
How can we make the calendar note of win10 computer display 24 solar terms?

SDN学习之Opendaylight浅析(三)
随机推荐
五一劳动节哪个理财产品收益高?
Detailed explanation of kubernetes (VII) -- service object deployment and Application
MySQL_00_初识MySQL
Exercises and answers of relevant laws and regulations in 2022 environmental impact assessment engineer examination
Redis(16) -- Redis集群
[unity] combat system learning 12: switchable
Test life | less than 2 years after graduation, 0 experience and won the 30W annual salary of a well-known Internet enterprise. How did he do it?
敬語 謙譲
JS中递归返回值为undefined
2022 technical guidelines and standard exercises and answers for environmental impact assessment engineer examination
7 capabilities of data analysis: sorting out data needs
DevExpress WPF入门指南 - 运行时生成的POCO视图模型(一)
[interview ordinary people vs Expert Series] please talk about the network quadruple
Globalmapper20 how to batch convert SHP to KML and bring attributes
Data security audit OTP configuration
[golang] force buckle leetcode - 657 Whether the robot can return to the origin (simulation)
ASP. Net core to realize JWT authorization and authentication (2. Practical part)
VSCode 最全实用插件(VIP典藏版)
remix连接测试链,连接Arbiturm二层网络
Typical application scenarios of alicloud log service SLS