ES6中的Proxy是一个强大的对象拦截器,它可以拦截对象的各种操作,比如属性访问、函数调用等。你可以使用Proxy来控制对象的访问和修改行为,从而实现一些高级特性。下面是使用Proxy的一些例子:
- const obj = {
- name: 'Tom',
- age: 18
- };
-
- const proxy = new Proxy(obj, {
- get(target, property) {
- console.log(`get ${property}`);
- return target[property];
- },
- set(target, property, value) {
- console.log(`set ${property}=${value}`);
- target[property] = value;
- }
- });
-
- proxy.name; // 访问name属性,会输出 "get name"
- proxy.age = 20; // 修改age属性,会输出 "set age=20"
- const obj = {
- add(a, b) {
- return a + b;
- }
- };
-
- const proxy = new Proxy(obj, {
- apply(target, thisArg, argumentsList) {
- console.log(`call add(${argumentsList.join(', ')})`);
- return target.apply(thisArg, argumentsList);
- }
- });
-
- proxy.add(1, 2); // 调用add方法,会输出 "call add(1, 2)"
- const obj = {
- name: 'Tom'
- };
-
- const proxy = new Proxy(obj, {
- deleteProperty(target, property) {
- console.log(`delete ${property}`);
- delete target[property];
- }
- });
-
- delete proxy.name; // 删除name属性,会输出 "delete name"
const obj = {