apply(): 拦截函数的调用、call和apply操作
var target = function () { return 'I am the target';};
var handler = {apply: function () {reuturn 'I am the proxy';}
};var p = new Proxy(target, handler);
p(); // " I am the proxy"
has(): 判断对象是否具有某个属性,典型的操作就是in运算符
var handler ={has (target, key) {if ( key[0] === '_') {return false;}return key in target;}
};
var target = { _prop: 'foo', prop: 'foo' };
var proxy = new Proxy(target, handler);
'_prop' in proxy // false// 注:has拦截对for...in循环不生效
let stu1 = {name: '张三', score: 59};
let stu2 = {name: '李四', score: 99};let handler = {has (target, prop) {if (prop === 'score' && target[prop] < 60) {console.log(target.name, '不及格');return false;}return prop in target;}
}
let oproxy1 = new Proxy(stu1, handler);
let oproxy2 = new Proxy(stu2, handler);'score' in oproxy1
// 张三不及格
// false
construct(): 用于拦截new命令
var p = new Proxy(function () {}, {construct: function (target, args) {console.log('called: ' + args.join(', ')):return { value: args[0] *10};}
});(new p(1)).value
// "called: 1"
// 10
deleteProperty(): 拦截delete操作
var handler = {deleteProperty (target, key) {invariant(key, 'delete');return true;}
};
function invariant (key, action) {if (key[0] === '_') {throw new Error('Invalid attempt to',action,'private', key,'property');}
}
var target = {_prop: 'foo' };
var proxy = new Proxy(target, handler);
delete proxy._prop
// Error: Invalid attempt to delete private "_prop" property
defineProperty(): 拦截Object.defineProperty操作
getOwnPropertyDescriptor(): 拦截Object.getOwnPropertyDescriptor()
getPrototypeOf(): 拦截获取对象原型
var proto = {};
var p = new Proxy({}, {getPrototypeOf(target) {return proto;}
});
Object.getPrototypeOf(p) === proto // true
isExtensible(): 拦截Object.isExtensible操作
ownKeys(): 拦截对象自身属性的读取操作
// 下面的例子是拦截第一个字符为下画线的属性名
let target = {_bar: 'foo',_prop: 'bar',prop: 'baz'
};let handler = {ownKeys (target) {return Reflect.ownKeys(target).fliter(key => key[0] !== '_');}
};let proxy = new Proxy(target, handler);
for ( let key of Object.keys(proxy)) {console.log(target[key]);
}
// "baz"
// 注:有三类属性会被 ownKeys方法自动过滤:
// ·目标对象不存在的属性
// ·属性名为Symbol值
// ·不可遍历的属性// 注:ownKeys方法返回的数组成员只能是字符串或 Symbol值.
preventExtensions(): 拦截Object.preventExtensions()
setPrototypeOf(): 拦截Object.setPrototypeOf()
参考《ES6标准入门》(第三版) P242~P255