ES6学习笔记(12)----Reflect
参考书《ECMAScript 6入门》
http://es6.ruanyifeng.com/
Reflect
1.概述:Object对象的内部方法都能在Reflect中找到,同时Reflect将Object的一些命令改成了函数操作,且Reflect与Proxy一一对应。
2.静态方法
Object,Reflect,Proxy对比
Reflect第一个参数是对象,如果不是,则报错
let s = Symbol("ss");
let obj = {
"color" : "black",
size : 12,
[s] : "test symbol"
}
let obj1 = {
"type" : "A"
}
function Animal(name){
this.name = name;
}
Object.defineProperty(obj,'nonEm',{
value : "123",
enumerable : false,
confirgurable : true,
writable : true
});
Reflect.defineProperty(obj,'nonCn',{
value : "er",
enumerable : true,
configurable : false,
writable : true
});
Object.keys(obj);// ["color", "size", "nonCn"]
Reflect.ownKeys(obj);//["color", "size", "nonEm", "nonCn", Symbol(ss)]
obj.color //'black'
obj['color'] //'black'
Reflect.get(obj,'color'); //'black'
obj.name = "add name";//'add name'
Reflect.set(obj,'name','add name');//true
'size' in obj //true
Reflect.has(obj,'size');//true
Object.getOwnPropertyDescriptor(obj,'name');//{value: "add name", writable: true, enumerable: true, configurable: true}
Reflect.getOwnPropertyDescriptor(obj,'name');//{value: "add name", writable: true, enumerable: true, configurable: true}
Object.setPrototypeOf(obj,obj1);//{color: "black", size: 12, nonCn: "er", name: "add name", nonEm: "123", …}
Reflect.setPrototypeOf(obj,obj1);//true
Object.getPrototypeOf(obj);//{type: "A"}
Reflect.getPrototypeOf(obj);//{type: "A"}
Object.isExtensible(obj);//true
Reflect.isExtensible(obj);//true
Object.preventExtensions(obj);//{color: "black", size: 12, nonCn: "er", name: "add name", nonEm: "123", …}
Reflect.preventExtensions(obj);//true
Object.isExtensible(obj);//false
Reflect.isExtensible(obj);//false
delete obj['color']//true
Reflect.deleteProperty(obj,'color');//true
Reflect.ownKeys(obj);//["size", "nonEm", "nonCn", "name", Symbol(ss)]
let cat = new Animal('cat');
let cat1 = Reflect.construct(Animal,'cat1');
3.观察者模式
let obj = {name : "test"}
let handler = {
set(target,propKey,propValue,receiver){
let origin = Reflect.set(target,propKey,propValue,receiver);
console.log("add " + propKey+ " = " + propValue + " to target");
return origin;
}
}
let proxy = new Proxy(obj,handler);
proxy.color = "red"; //add color = red to target "red"
将观察对象与反应行为改为动态参数
let fs = new Set();
let objTest = {name : "123"};
let action = function(t,k,v){
console.log("add new attributes");
}
let observe = function(fn){
fs.add(fn);
}
let observeObj = function(obj){
return new Proxy(obj,{
set(target,propKey,propValue,receiver){
let origin = Reflect.set(target,propKey,propValue,receiver);
fs.forEach(fn => fn());
return origin;
}
});
}
observe(action);
let x = observeObj(objTest);
x.color = "455";//add new attributes "455"