![](/img/trans.png)
[英]Javascript List of Objects in IE<9 fail to inherit from Object.prototype
[英]Why numbers are not instances of Object while they inherit from Object.prototype?
請參閱以下代碼段。
let num = 3; Object.prototype.prop = "something"; console.log(num instanceof Object); //false; console.log(num.hasOwnProperty('prop')) //false console.log(num.prop) //'something'
有人可以解釋為什么num instanceof Object
和num.hasOwnProperty('prop')
返回false
但我們仍然可以在num
上訪問Object.prototype
的屬性
數字是原語 ,因此它們不會從Object
繼承而不是任何instanceof
。
但是,當您嘗試訪問屬性(例如方法)時,Javascript會將數字裝入Number
對象,以便此屬性訪問實際上是在即時創建的Number
對象上。 就像你做的那樣:
console.log((new Number(num)).constructor.name);
console.log((new Number(num)).hasOwnProperty('prop'));
console.log((new Number(num)).prop):
prop
將在原型鏈中找到Number
對象,但hasOwnProperty
-顧名思義- 不看原型鏈,因此不會考慮你放什么在Object.prototype
。
請注意,當您不嘗試訪問屬性時,不會發生此靜默裝箱,因此在num instanceof
中考慮原語,而不是它的Number
變體。
您可以通過調用toSource
方法實際看到該裝箱的toSource
:
let num = 5; console.log(num.toSource());
有趣的事實:你可以用數字文字得到這個拳擊 - 它需要第二個點來消除小數點的歧義:
console.log(1..toSource());
EcmaScript規范在屬性訪問器一節中定義了此過程。 評估依賴於
GetValue(propertyNameReference).
反過來,它在流程定義中有這個:
If IsPropertyReference(V) is true, then If HasPrimitiveBase(V) is true, then Assert: In this case, base will never be undefined or null. Set base to ! ToObject(base).
最后ToObject
執行實際的包裝。
只有實際的對象才能將其instanceof
任何內容解析為true
。 請參閱instanceof
上的規范 ,它指向HasInstance
:
當使用值V調用F的[[HasInstance]]內部方法時,將執行以下步驟:
- 如果V不是對象,則返回false。
數字甚至不是instanceof Number
:
console.log(1 instanceof Number);
但是,如果你使用了new Number
(你不應該)並創建了一個實際的數字對象,它將按預期工作:
console.log(new Number(1) instanceof Number);
hasOwnProperty()
方法返回一個布爾值,指示對象是否具有指定的屬性作為其自己的屬性( 而不是繼承它 )。
強調我的
該數字繼承該屬性,因此您可以訪問它,但它沒有被定義為數字本身的屬性,這就是為什么hasOwnProperty("prop")
返回false。
instanceof
失敗的原因是因為它只能用於顯式對象(構造或文字)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.