一、Proxy代理
如果不直接操作对象,而是像代理模式,通过对象的代理对象进行操作,在进行这些操作时,可以添加一些需要的额外操作,譬如进行拦截。
//定义一个类
const employee = {
firstName: 'Tapas',
lastName: 'Adhikary'
};
//定义一个处理
let handler = {
get: function(target, fieldName) {
if(fieldName === 'fullName' ) {
return `${target.firstName} ${target.lastName}`;
}
return fieldName in target ?
target[fieldName] :
`No such property as, '${fieldName}'!`
}
};
//定义一个代理
let p = new Proxy(employee, handler);
//调用
console.group('proxy');
console.log(p.firstName);
console.log(p.lastName);
console.log(p.org);
console.log(p.fullName);
console.groupEnd()
//输出
proxy
Tapas
Adhikary
No such property as, 'org'!
Tapas Adhikary
二、reflect
Reflect是ES6为操作对象的属性或方法,更详细解释请参看官方文档,这里只是先给一个基本理解。
//Reflect一共有13个静态方法
Reflect.apply(target, thisArg, args)
Reflect.construct(target, args)
Reflect.get(target, name, receiver)
Reflect.set(target, name, value, receiver)
Reflect.defineProperty(target, name, desc)
Reflect.deleteProperty(target, name)
Reflect.has(target, name)
Reflect.ownKeys(target)
Reflect.isExtensible(target)
Reflect.preventExtensions(target)
Reflect.getOwnPropertyDescriptor(target, name)
Reflect.getPrototypeOf(target)
Reflect.setPrototypeOf(target, prototype)
//示例1 Reflect.apply
// 老写法
Function.prototype.apply.call(Math.floor, undefined, [1.75]) //返回: 1
// 新写法
Reflect.apply(Math.floor, undefined, [1.75]) // 返回:1
//示例2 Reflect.get
let obj = {
name: 'dreamapple',
age: 22,
get money() {
console.log(`I can tell you my name ${this.name}, but not my money`);
return 0
}
};
console.log(Reflect.get(obj, 'name')); // dreamapple
console.log(Reflect.get(obj, 'myName')); // undefined
console.log(Reflect.get(obj, 'money'));
console.log(Reflect.get(obj, 'money', {name: 'happy'}));
// I can tell you my name happy, but not my money // 0
//示例3 Reflect.defineProperty
let obj = {};
let obj1 = Object.defineProperty(obj, 'name', {
enumerable: true,
value: 'dreamapple'
});
console.log(obj); // { name: 'dreamapple' }
//示例4Reflect.deleteProperty
const myObj = { foo: 'bar' };
// 旧写法
delete myObj.foo;
// 新写法
Reflect.deleteProperty(myObj, 'foo');