[英]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
轉換為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.