proxy在语言层面去操作一个对象
var user={}; user.fname='Bob'; user.lname="Wood"; user.fullName= function () { console.log(this.fname+" "+this.lname); } user.fullName();//Bob Wood
现在要做到user.fullName就让它去显示。
proxy接收2个参数,第一个是对象{},第二个也是个{}。
var user = new Proxy({}, { get: function (obj, prop) { return obj.fname + " " + obj.lname; } }); user.fname = 'Bob'; user.lname = "Wood"; console.log("user.fullName:" + user.fullName); //user.fullName:Bob Wood
此时没有对传入get方法中的prop做判断。所以哪怕输入一个user.age也会输出:Bob Wood
console.log("user.age:" + user.age); //user.age:Bob Wood
所以做一个判断,如果prop是full_name就输出全名
var user = new Proxy({}, { get: function (obj, prop) { if(prop=='full_name'){ return obj.fname + " " + obj.lname; } } }); user.fname = 'Bob'; user.lname = "Wood"; console.log("user.full_name:" + user.full_name); //user.full_name:Bob Wood console.log("user.age:" + user.age); //user.age:undefined
也可以通过switch对多个prop进行处理
var user = new Proxy({}, { get: function (obj, prop) { switch (prop){ case 'full_name': return obj.fname + " " + obj.lname; case 'age': return obj.age; } } }); user.fname = 'Bob'; user.lname = "Wood"; user.age="25"; console.log("user.full_name:" + user.full_name); //user.full_name:Bob Wood console.log("user.age:" + user.age); //user.age:25
总结:get就像一层过滤器一样,obj在取值前加了一层,在对象提取值之前做一些操作。
除了get,也可以用set在设置属性时做一层处理。
var user = new Proxy({}, { get: function (obj, prop) { switch (prop) { case 'full_name': return obj.fname + " " + obj.lname; case 'age': return obj.age; } }, set: function (obj, prop,value) {//针对不同属性set值 switch (prop) { case 'age': obj.age=value+"岁"; break; default: obj[prop]=value; //age之外的属性直接保存 break; } } }); user.fname = 'Bob'; user.lname = "Wood"; user.age = "25"; console.log("user.full_name:" + user.full_name); //user.full_name:Bob Wood console.log("user.age:" + user.age); //user.age:25岁
除了get ,set 还有一些方法如下:
var handler = { // target.prop get: ..., // target.prop = value set: ..., // 'prop' in target has: ..., // delete target.prop deleteProperty: ..., // target(...args) apply: ..., // new target(...args) construct: ..., // Object.getOwnPropertyDescriptor(target, 'prop') getOwnPropertyDescriptor: ..., // Object.defineProperty(target, 'prop', descriptor) defineProperty: ..., // Object.getPrototypeOf(target), Reflect.getPrototypeOf(target), // target.__proto__, object.isPrototypeOf(target), object instanceof target getPrototypeOf: ..., // Object.setPrototypeOf(target), Reflect.setPrototypeOf(target) setPrototypeOf: ..., // for (let i in target) {} enumerate: ..., // Object.keys(target) ownKeys: ..., // Object.preventExtensions(target) preventExtensions: ..., // Object.isExtensible(target) isExtensible :... }
参考:http://wiki.jikexueyuan.com/project/es6/object.html
本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/6919862.html有问题欢迎与我讨论,共同进步。