微信小程序數(shù)據(jù)劫持代理的實(shí)現(xiàn)
index.html
index.js
// Vue數(shù)據(jù)劫持代理 //模擬Vue中data選項(xiàng) let data = { username:'小鐳', age:3 } // 模擬組件的實(shí)例 let _this={} // 利用object.defineProperty() for(let item in data){ console.log(item,data[item]); Object.defineProperty(_this,item,{ // get作用:用來獲取擴(kuò)展屬性值,當(dāng)獲取該屬性時調(diào)用get方法 get(){ console.log('get()'); return data[item] } }) } console.log(_this)
當(dāng)要獲取訪問age或username的值時,才會調(diào)用get()方法,打印get()
若要修改data中的username的 值,可以直接通過_this.username修改嗎?
答案是:不可以
(沒有修改成功,username還是“小鐳")
可以通過set方法修改值
for(let item in data){ console.log(item,data[item]); Object.defineProperty(_this,item,{ // get作用:用來獲取擴(kuò)展屬性值,當(dāng)獲取該屬性時調(diào)用get方法 get(){ console.log('get()'); return data[item] }, //set作用:監(jiān)視擴(kuò)展屬性的,只要已修改就調(diào)用 set(newValue){ console.log('set()',newValue); // _this.username=newValue; 千萬不要在set方法中修改當(dāng)前擴(kuò)展屬性的值,會出現(xiàn)死循環(huán) data[item] = newValue; } }) }
(修改成功!)
到此這篇關(guān)于微信小程序數(shù)據(jù)劫持代理的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)小程序數(shù)據(jù)劫持代理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS代碼實(shí)現(xiàn)根據(jù)時間變換頁面背景效果
這篇文章主要介紹了JS代碼實(shí)現(xiàn)根據(jù)時間變換頁面背景效果的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友一起看下吧2016-06-06JavaScript中各種編碼解碼函數(shù)的區(qū)別和注意事項(xiàng)
JavaScript 中encodeURI,encodeURIComponent與escape的區(qū)別和注2010-08-08