ES6入门教程入门教程——7、、ES6 Reflect 与与 Proxy
一、一、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
评论0
最新资源