问题描述
如果我们像这样向Number函数(或Boolean或String)添加一个方法
If we add a method to Number function (or Boolean or String) like this
Number.prototype.sayMyNumber = function(){
return "My number is " + this;
}
然后创建一个数字对象,将其分配给变量
and then create a number object assign it to a variable
var num1 = new Number(34);
num1.sayMyNumber(); // it says "My number is 34"
这很好,并且在我们创建"Number"对象时可以预期.
This is fine and expected as we created 'Number' object.
类似地,如果我创建一个原始变量
Similarly, if I create a primitive variable
num2 = 34;
num2.sayMyNumber(); // it says "My number is 34"
令人惊讶的是,即使我们没有显式创建Number对象,num2也具有方法sayMyNumber().
Surprisingly, num2 also has a method sayMyNumber() even though we did not create a Number object explicitly.
然后我像这样尝试
34.sayMyNumber(); // error, this does not work
为什么num2起作用?
Why does num2 work?
更新
这是我在评论部分中提出的跟进问题,我将其放在此处以提高可见度
下面的答案提到num2在内部被视为数字"对象.这进一步使我感到困惑.
Below answers mention that num2 is considered as a 'Number' object internally. This further confuses me.
typeof num1 === "number" // returns false
typeof num2 === "number" // returns true
typeof num1 === "object" // returns true
typeof num2 === "object" // returns false
这不是说num2不是对象"吗?如果它不是对象",那么它怎么可能是"Number"的实例?
Does this not mean that num2 is not an "object" ?If it is not an "object" then how can it be an instance of 'Number' ?
推荐答案
原始类型 Number 具有相应的对象表示形式,可以使用 new Number
创建该对象表示形式.这是一个对象,因此与原始类型 Number 具有不同的数据类型.
The primitive type Number has a corresponding object representation, which you can create with new Number
. This is an object and is therefore of a different data type than the primitive type Number.
如果调用 Number(34)
(没有 new
),则不会创建对象,但是Number函数将类型转换为原始数字值.
If you call Number(34)
(without new
) an object isn't created, but the Number function performs a type conversion, to a primitive number value.
var num1 = new Number(34); // object
var num2 = 34; // primitive
当您在基元编号 num2
上调用 sayMyNumber()
时,JavaScript会在内部将基元临时转换为等效的对象版本.并且由于您在 Number.prototype
中添加了 sayMyNumber()
,因此您可以访问该函数.
When you call sayMyNumber()
on the primitive number num2
, JavaScript internally converts the primitive temporarily to its equivalent object version. And because you added sayMyNumber()
to Number.prototype
you have access to the function.
34.sayMyNumber()
不起作用的原因是,当JavaScript引擎解析您的源代码时,它必须解释给定上下文中点的含义.在 34.sayMyNumber()
的情况下,该点可能是模棱两可的.它是指小数点分隔符吗?还是意味着对象成员访问?JavaScript选择解释所有整数,后跟一个点,以表示浮点数的一部分.但是由于没有这样的数字34.sayMyNumber(),因此会引发SyntaxError.在此处了解详情
The reason 34.sayMyNumber()
doesn't work is because when JavaScript engine parses your source code, it has to interpret just what a dot means in a given context. In the case of 34.sayMyNumber()
the dot is potentially ambiguous. Does it mean the decimal separator? Or does it mean object member access? JavaScript opts to interpret all integers followed by a dot as representing part of a floating point number. But as there is no such number 34.sayMyNumber(), it raises a SyntaxError. Read more here
这篇关于为什么原始变量的行为像对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!