代理模式#####
let data = [
{ "id": 1, "name": "小猪佩奇1", "price": 100, "zhek": 1 },
{ "id": 2, "name": "小猪佩奇2", "price": 200, "zhek": 1 },
{ "id": 3, "name": "小猪佩奇3", "price": 300, "zhek": 0 },
{ "id": 4, "name": "小猪佩奇4", "price": 400, "zhek": 0 }
]
//Proxy get方法是在调用时生效,如itemData = getZheK(itemData) 此时itemData仍为未改变值 只有 itemData.name(调用时)会实时进行里面的判断
function getZheK(itemData){
return new Proxy(itemData, {
get: function (target, key) {
if (key === 'name') {
return `${target[key]} 【折扣】`
}
if (key === 'price') {
return target[key] * 0.8
}
return target[key]
}
})
}
let b = data.map(itemData => {
if(itemData.zhek) {
itemData = getZheK(itemData)
}
//虽然表面上是没改变,但循环获得值时会计算出相应值
console.log('呈现的itemData没有改变:', itemData, `, 实际调用itemData.name: ${itemData.name}, 实际调用itemData.price: ${itemData.price}`)
/*
*打印值:
*呈现的itemData没有改变: Proxy {id: 1, name: "小猪佩奇1", price: 100, zhek: 1} , 实际调用itemData.name: 小猪佩奇1 【折扣】, 实际调用itemData.price: 80
*呈现的itemData没有改变: Proxy {id: 2, name: "小猪佩奇2", price: 200, zhek: 1} , 实际调用itemData.name: 小猪佩奇2 【折扣】, 实际调用itemData.price: 160
*呈现的itemData没有改变: {id: 3, name: "小猪佩奇3", price: 300, zhek: 0} , 实际调用itemData.name: 小猪佩奇3, 实际调用itemData.price: 300
*呈现的itemData没有改变: {id: 4, name: "小猪佩奇4", price: 400, zhek: 0} , 实际调用itemData.name: 小猪佩奇4, 实际调用itemData.price: 400
*/
return itemData
})
从上面例子可以得出: 1.get方法在调用时执行逻辑 2.逻辑处理时可以根据 target key 重置该字段值 而不用改变原数据 3.在循环后调用值符合预期