zoukankan      html  css  js  c++  java
  • 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.其他场景待完善

  • 相关阅读:
    easyui tree:根据属性格式化树节点名称
    Druid执行多条SQL异常:Cause: java.sql.SQLException: sql injection violation, multi-statement not allow
    springmvc接收jquery提交的数组数据
    jquery easyui:tab自动加载第一个tab内容
    thymeleaf-extras-shiro
    Shiro:授权控制
    thymeleaf : EL1050E The arguments (...) for the constructor call are missing
    (转载)ibatis:解决sql注入问题
    05 Oracle process
    04 memory structure
  • 原文地址:https://www.cnblogs.com/knyel/p/7842707.html
Copyright © 2011-2022 走看看