簡體   English   中英

typeof為`this`返回“object”,在其他地方返回“number”

[英]typeof returns “object” for `this`, “number” elsewhere

當在不同的上下文中應用於相同的值時, typeof計算為不同的字符串。 例如,這是預期的:

> typeof 5
'number'

......然而,在typeof 5時,通過訪問this是不一樣的:

> Number.prototype.foo = function () { return typeof this; };
[Function]
> (5).foo()
'object'

只是另一個(in)健全性檢查,真的,認真驗證this 一個數字:

> Number.prototype.foo = function () { return [this + 1, typeof this]; };
[Function]
> (5).foo()
[ 6, 'object' ]

我已經閱讀了MDN文檔和ECMAScript規范中的typeof ,並且無法想象這是如何預期的,無所謂正確。 有人有解釋嗎?

這里的訣竅是你的測試用例改變了5個對象。

每當您訪問原始值(布爾值,數字或字符串)的屬性時,原始值將轉換為適當類型的對象(布爾值,數字或字符串),並在該對象上解析屬性訪問。

我在這里這里寫了更多關於這個主題的文章

顯示類型的正確方法是:

Number.prototype.foo = function () { return typeof this.valueOf(); };
(5).foo() // "number"

當您執行this+1時,您的完整性檢查會將對象包裝器轉換回原始值this+1

(new Number(5)) + 1 // 6

我的猜測是(5)將原始類型number轉換為Number對象。

嘗試添加這樣的函數:

Number.prototype.foo2 = function() { console.log(this); }

你打電話給(5).foo2()后,你會在Chrome中得到這樣的結果:

Number {foo: function, foo2: function}
    __proto__: Number
    [[PrimitiveValue]]: 5

暫無
暫無

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

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