时间:2022-06-18 12:38:54 | 栏目:JavaScript代码 | 点击:次
Proxy 对象用于拦截并修改目标对象的指定操作。
// 语法 const p = new Proxy(target, handler)
访问不存在的属性,设置默认值返回而不返回 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
let target = {}; let p = new Proxy(target, {}); p.a = 37; // 操作转发到目标 console.log(target.a); // 37. 操作已经被正确地转发
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
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