关于javascript:自定义proxy检测异常数据

5次阅读

共计 1022 个字符,预计需要花费 3 分钟才能阅读完成。

// 批改对象某个属性值拦挡

            const validator = {set:function (target,prop,value){if(prop === 'productNum'){if(value > 200){throw new Error('库存有余')
                        }
                    }
                    target[prop] = value
                }
            }
            var products = new Proxy({},validator);
            products.productNum = 300;

// 检测对象特定属性的数据
            let data = [ //getProductList
            {    
                id:1,
                product:{
                    productName:'aaa',
                    productDesc:'this is white Lu'
                },
                stock:null
                
            },
            {
                id:2,
                product:{
                    productName:'bbb',
                    productDesc:'this is taylon lu'
                },
                stock:{
                    productColor:'yellow',
                    productNum:14,
                    id:2
                }
                
            },
            {
                id:3,
                product:{
                    productName:'ccc',
                    productDesc:'this is lu zhi'
                },
                stock:{
                    productColor:'black',
                    productNum:14,
                    id:3
                }
                
            },
            {
                id:4,
                product:{
                    productName:'ddd',
                    productDesc:'this is JR'
                },
                stock:{
                    productColor:'green',
                    productNum:null,
                    id:4
                }
                
            }
        ]
            const validatorData = {get:function (target,propKey,receiver){
                    let dataId = target.id;
                    if(propKey === 'stock'){
                        try {if(target[propKey] === null){alert('第' + dataId + '条数据库存对象为 null')
                            
                            }else if(target[propKey].productNum === null){alert('库存表下第' + target[propKey].id + '条数据的库存数量为 null, 请及时处理')
                            }    
                        }catch(ex){throw new Error(ex)
                        }
                        
                    }
                }
            }
            data.forEach((item,index)=>{item = new Proxy(item,validatorData);
                item.stock // 检测 stock 对象
            })
正文完
 0