typeof返回“对象”对于'this`,“number”别处 [英] typeof returns "object" for `this`, "number" elsewhere

查看:110
本文介绍了typeof返回“对象”对于'this`,“number”别处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typeof 在应用于不同上下文中的相同值时计算为不同的字符串。例如,这是预期的:

typeof evaluates to different strings when applied to the same value in different contexts. For example, this is expected:

> typeof 5
'number'

...然而, typeof 5 当通过访问时,此不一样:

...and yet, the typeof 5 when accessed via this is not the same:

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

另一个(in)健全性检查,要真的,认真验证 一个数字:

Just another (in)sanity check, to really, seriously verify that this is a number:

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

我是阅读MDN文档和 ECMAScript规范 typeof ,无法想象这是怎么回事,没关系。有没有人有解释?

I've read through the MDN docs and the ECMAScript spec for typeof, and can't imagine how this is to be expected, nevermind correct. Does anyone have an explanation?

推荐答案

这里的诀窍是你的测试用例将5更改为一个对象。

The trick here is that your test case changes 5 to an object.

每当您访问原始值(布尔值,数字或字符串)的属性时,原始值将转换为适当类型的对象(布尔值,数字或字符串)和属性访问权限已在该对象上解决。

Whenever you access a property on a primitive value(boolean, number or string), the primitive value is converted to an object of the appropriate type (Boolean, Number or String) and the property access is resolved on that object.

我已经在此处此处

显示的正确方法type是:

The correct method to show the type is:

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

您的理智检查转换为当您执行此+ 1 时,对象包装器返回原始值:

Your sanity check converts the Object wrapper back to the primitive value when you do this+1:

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

这篇关于typeof返回“对象”对于'this`,“number”别处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆