1分鐘學(xué)會(huì)如何用 JS 對(duì)象代理(proxies)實(shí)現(xiàn)對(duì)象的私有屬性
今天我們來(lái)聊聊私有屬性,在其他的高級(jí)語(yǔ)言中很容易能實(shí)現(xiàn)私有屬性的功能,那么在 JS 中怎么實(shí)現(xiàn)對(duì)象的私有屬性呢,首先我們聊聊私有屬性運(yùn)用的需求場(chǎng)景,比如我們?cè)趯?duì)象里用 _ 符號(hào)開(kāi)頭的形式定義對(duì)象的私有屬性,不希望外部環(huán)境讀取私有屬性,如下段代碼所示
let?bankAccount?=?{
????holderName:?'Joe',
????currency:?'USD',
????_balance:?1000
}
我們希望讀取對(duì)象 ?_balance 的私有屬性或刪除對(duì)象的 _balance 屬性,會(huì)有如下的提示:
//?don't?allow?reading?the?balance
console.log(bankAccount._balance);
//?don't?allow?deleting?the?property
delete?_balance
那我們?cè)撊绾螌?shí)現(xiàn)呢?這時(shí)候我們可以使用 JS 代理,針對(duì) _符號(hào)開(kāi)頭的私有屬性進(jìn)行特殊的邏輯處理(你也可以用其他的符號(hào)自定義私有屬性),廢話不多說(shuō),上代理的實(shí)現(xiàn)的代碼邏輯,以下為代理攔截器方法的代碼:
let?proxyHandler?=?{?
????has:?(target,?prop)?=>?{?
????????if(prop.startsWith(prefix)){?
????????????return?false;
????????}?
????????return?prop?in?target?
????},?//?針對(duì)?in?方法的重寫(xiě)
????ownKeys:?target?=>?{?
????????return?Reflect.ownKeys(target).filter(?
????????????prop?=>?!prop.startsWith(prefix)?
????????)?
????},?//針對(duì)?keys?方法的重寫(xiě)
????get:?(target,?prop)?=>?{?
????????if(prop.startsWith(prefix))?{?
????????????return?undefined;?
????????}?
????????return?target[prop];?
????},?
????deleteProperty(target,?prop)?{?
????????if?(prop.startsWith('_'))?{?
????????????return?true;?//私有屬性不刪除
????????}?else?{?
????????????delete?target[prop];?
????????????return?true;?
????????}
????}
}
接下來(lái),我們來(lái)驗(yàn)證下上述代碼是否可行:
const?hidePrivateFields?=?(target,?prefix?=?"_")?=>?{?
????return?new?Proxy(target,?proxyHandler)
};
let?bankAccount?=?hidePrivateFields({
????holderName:?'Joe',
????currency:?'USD',
????_balance:?1000
})
console.log(bankAccount._balance)?//?undefined?
console.log('_balance'?in?bankAccount)?//false
console.log(Object.keys(bankAccount))?//?['holderName',?'currency']?
console.log(delete?bankAccount._balance)?//?returns?true,?but?does?not?delete?the?balance
今天關(guān)于 JS 對(duì)象代理在私有屬性方面的應(yīng)用就分享到這里,下一篇文章,我們將繼續(xù)分享代理有趣的應(yīng)用,比如以前JQ 插件庫(kù)可以通過(guò)鏈?zhǔn)秸Z(yǔ)法很容易的操控樣式,如下所示,如果讓你用 JS 對(duì)象代理,你會(huì)如何實(shí)現(xiàn)呢?
style(".menu").color("#fff").backgroundColor("#000").opacity("1");
文章來(lái)源:http://www.js-craft.io/blog/javascript-proxies-restricting-access-to-object-properties-and-some-other-practical-examples/ ??
作者:Daniel
點(diǎn)擊卡片,關(guān)注我吧~
