簡體   English   中英

如果我不保留 Object.defineProperty 描述符屬性會怎樣?

[英]what happens if I didn't preserve Object.defineProperty descriptor attributes?

MDN 文檔上,我無法理解有關Object.defineProperty descriptor的這一部分:

請記住,這些屬性不一定是描述符自己的屬性。 繼承的屬性也將被考慮在內。 為了確保保留這些默認值,您可以預先凍結 Object.prototype,明確指定所有選項,或使用 Object.create(null) 指向 null。

如果我不保留描述符屬性會怎樣? 有沒有可能發生意想不到的事情? 請舉個例子?

這是 IMO 的一個非常特殊的建議,僅用於非常防御性的代碼。 舉個例子:

您可能會預先凍結 Object.prototype,明確指定所有選項,或者使用 Object.create(null) 指向 null。

如果你不這樣做,那么如果你碰巧有代碼突變Object.prototype (在任何理智的情況下你真的不應該這樣做),並且突變的Object.prototype添加了描述符使用的屬性,這些屬性將即使它們不直接在 object 上也可以使用。像這樣:

 // FOR INFORMATIONAL USE ONLY // NEVER USE THIS NEXT LINE IN REAL CODE Object.prototype.writable = true; // then later: const obj = {}; Object.defineProperty(obj, 'prop', { value: 'value' }); /* In normal circumstances, the resulting descriptor would be: { value: 'value', enumerable: false, writable: false, configurable: false, } But because `writable` was inherited from Object.prototype is true, the property is writable: */ obj.prop = 'value2'; console.log(obj.prop);

一個可能的補救方法是提前凍結Object.prototype ,這樣就不可能發生這樣的突變:

 'use strict'; // so error below is explicit Object.freeze(Object.prototype); // FOR INFORMATIONAL USE ONLY // NEVER USE THIS NEXT LINE IN REAL CODE Object.prototype.writable = true;

或者確保創建的描述符 object 不繼承自Object.prototype

 // FOR INFORMATIONAL USE ONLY // NEVER USE THIS NEXT LINE IN REAL CODE Object.prototype.writable = true; // then later: const obj = {}; const descriptor = Object.create(null); descriptor.value = 'value'; Object.defineProperty(obj, 'prop', descriptor); obj.prop = 'value2'; console.log(obj.prop);

或者顯式寫出描述符的所有值,而不依賴默認值:

 // FOR INFORMATIONAL USE ONLY // NEVER USE THIS NEXT LINE IN REAL CODE Object.prototype.writable = true; // then later: const obj = {}; Object.defineProperty(obj, 'prop', { value: 'value', enumerable: false, writable: false, configurable: false, }); obj.prop = 'value2'; console.log(obj.prop);

但在任何遠程理智的代碼中,這些都不是必需的,因為Object.prototype不應該從一開始就被改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM