ES6 Proxy的應用場景


一、相關API

Proxy

Reflect

二、Proxy應用場景

1.數據校驗

表單提交的時候做數據校驗,例如年齡是不是滿足條件,數據類型是不是滿足要求等等,這場場景非常適合使用Proxy。

下面展示與業務解耦的校驗功能

1)ES6實現方式

{
    function validator(target, validator) {
        return new Proxy(target, {
            _validator: validator,
       //set方法用來攔截某個屬性的賦值操作,可以接受四個參數,依次為目標對象、屬性名、屬性值和 Proxy 實例本身,其中最后一個參數可選。 set(target, key, value, proxy) {
if (target.hasOwnProperty(key)) { let va = this._validator[key] if (!!va(value)) { return Reflect.set(target, key, value, proxy) } else { throw Error(`不能設置${key}到${value}`) } } else { throw Error(`${key}不存在`) } } }) } const personValidators = { name(val) { return typeof val === 'string' }, age(val) { return typeof val === 'number' && val > 18 } } class Person { constructor(name, age) { this.name = name; this.age = age return validator(this, personValidators) } } const person = new Person('knyel', 30) console.log(person) person.name = 'lk' console.log(person) person.age = 12 console.log(person) }

輸出結果為

Proxy {name: "knyel", age: 30}
Proxy {name: "lk", age: 30}
Uncaught Error: 不能設置age到12
    at Object.set (index.js:144)
    at Object.<anonymous> (index.js:174)
    at __webpack_require__ (index.js:20)
    at Object.obj.time (index.js:80)
    at __webpack_require__ (index.js:20)
    at Object.<anonymous> (index.js:70)
    at __webpack_require__ (index.js:20)
    at index.js:63
    at index.js:66

 

2)ES5實現方式

傳統的方式對某個屬性進行限制的時候,需要對他進行判斷,判斷類型是不是合適,是不是滿足某種條件,然后才允許它進行修改。

3)對比

用了ES6代理的方式,可以將條件和對象本身(業務邏輯)完全隔離開,后期代碼維護中,比如要加一個手機號的驗證,我們只需要在修改類Person(添加手機號屬性),personValidators(添加手機號驗證規則),這樣就可以實現了。代碼的擴展性、可維護性和健壯性是非常強的。

2.其他場景待完善


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM