在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、Proxy 是什么?Proxy 对象用于拦截并修改目标对象的指定操作。 // 语法 const p = new Proxy(target, handler)
二、怎么用?1、使用 Proxy 的简单实例访问不存在的属性,设置默认值返回而不返回 undefined // 1、找到合适的 handler 并编写代码 const handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; } }; // 2、新建 Proxy 对象 const p = new Proxy({}, handler); // 3、执行操作 p.a = 1; p.b = undefined; // 4、查看结果 console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37 2、目标对象被正确修改let target = {}; let p = new Proxy(target, {}); p.a = 37; // 操作转发到目标 console.log(target.a); // 37. 操作已经被正确地转发 3、使用 set handler 做数据验证let validator = { set: function(obj, prop, value) { if (prop === 'age') { if (!Number.isInteger(value)) { throw new TypeError('The age is not an integer'); } if (value > 200) { throw new RangeError('The age seems invalid'); } } // The default behavior to store the value obj[prop] = value; // 表示成功 return true; } }; let person = new Proxy({}, validator); person.age = 100; console.log(person.age); // 100 person.age = 'young'; // 抛出异常: Uncaught TypeError: The age is not an integer person.age = 300; // 抛出异常: Uncaught RangeError: The age seems invalid 4、扩展构造函数function extend(sup, base) { var descriptor = Object.getOwnPropertyDescriptor( base.prototype, "constructor" ); base.prototype = Object.create(sup.prototype); var handler = { construct: function(target, args) { var obj = Object.create(base.prototype); this.apply(target, obj, args); return obj; }, apply: function(target, that, args) { sup.apply(that, args); base.apply(that, args); } }; var proxy = new Proxy(base, handler); descriptor.value = proxy; Object.defineProperty(base.prototype, "constructor", descriptor); return proxy; } var Person = function (name) { this.name = name }; var Boy = extend(Person, function (name, age) { this.age = age; }); Boy.prototype.sex = "M"; var Peter = new Boy("Peter", 13); console.log(Peter.sex); // "M" console.log(Peter.name); // "Peter" console.log(Peter.age); // 13 总结本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注极客世界的更多内容! |
请发表评论