簡體   English   中英

為什么數字在從Object.prototype繼承時不是Object的實例?

[英]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 Objectnum.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]]內部方法時,將執行以下步驟:

  1. 如果V不是對象,則返回false。

數字甚至不是instanceof Number

 console.log(1 instanceof Number); 

但是,如果你使用了new Number (你不應該)並創建了一個實際的數字對象,它將按預期工作:

 console.log(new Number(1) instanceof Number); 

MDN上的hasOwnProperty

hasOwnProperty()方法返回一個布爾值,指示對象是否具有指定的屬性作為其自己的屬性( 而不是繼承它 )。

強調我的

該數字繼承該屬性,因此您可以訪問它,但它沒有被定義為數字本身的屬性,這就是為什么hasOwnProperty("prop")返回false。

instanceof失敗的原因是因為它只能用於顯式對象(構造或文字)。

暫無
暫無

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

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