사용자 정의 proxy 검사 이상 데이터

2850 단어 javascriptes6
//수정 대상의 속성 값 차단
            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 
            })

좋은 웹페이지 즐겨찾기