基本
您可能不知道,但是在JavaScript中,每当我们与字符串,数字或布尔基元进行交互时,我们都会进入对象阴影和强制的隐藏世界。
字符串,数字,布尔值,null,未定义和符号。
在JavaScript中有7种基本类型:undefined
,null
,boolean
,string
,number
,bigint
和symbol
。其他一切都是对象。基本类型boolean
,string
并且number
可以由它们的对象对应物包装。这些对象的实例Boolean
,String
并Number
分别构造。
typeof true; //"boolean"
typeof new Boolean(true); //"object"
typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"
typeof 123; //"number"
typeof new Number(123); //"object"
如果基元没有属性,为什么要"this is a string".length
返回值?
因为JavaScript会很容易在基元和对象之间强制转换。在这种情况下,字符串值被强制转换为字符串对象,以访问属性长度。字符串对象仅用了不到一秒钟的时间,之后便被献给了垃圾收集之神–但是,根据电视发现节目的精神,我们将捕获这种难以捉摸的生物并将其保存以备进一步分析……
为了进一步说明这一点,请考虑以下示例,在该示例中,我们向String构造函数原型添加了一个新属性。
String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty; // 5
通过这种方式,原语可以访问由它们各自的对象构造函数定义的所有属性(包括方法)。
因此,我们看到了基本类型将在需要时适当地强制转换为它们各自的Object对应对象。
分析toString()
方法
考虑以下代码
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
myObj.toString(); // "[object Object]"
myFunc.toString(); // "function(){}"
myString.toString(); // "This is a sample String"
myNumber.toString(); // "4"
myArray.toString(); // "2,3,5"
如上所述,真正发生的是,当我们toString()
在原始类型上调用方法时,必须先将其强制转换为对象的对等物,然后才能调用该方法。
即myNumber.toString()
相当于Number.prototype.toString.call(myNumber)
与其他基本类型并类似。
但是,如果不是将原始类型传递到toString()
其对应的Object构造函数的对应方法中,而是强制将原始类型作为参数传递到toString()
Object函数构造函数(Object.prototype.toString.call(x)
)的方法上呢?
仔细看看Object.prototype.toString()
根据文档,在调用toString方法时,将执行以下步骤:
- 如果
this
值为undefined
,则返回"[object Undefined]"
。
- 如果
this
值为null
,则返回"[object Null]"
。
- 如果此值不是上述所有值,则为
O
调用toObject
传递该this
值作为参数的结果。
- 设class为的
[[Class]]
内部属性的值O
。
- 返回字符串值是串联的三根弦的结果
"[object "
,class
和"]"
。
从以下示例了解这一点
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
var myUndefined = undefined;
var myNull = null;
Object.prototype.toString.call(myObj); // "[object Object]"
Object.prototype.toString.call(myFunc); // "[object Function]"
Object.prototype.toString.call(myString); // "[object String]"
Object.prototype.toString.call(myNumber); // "[object Number]"
Object.prototype.toString.call(myArray); // "[object Array]"
Object.prototype.toString.call(myUndefined); // "[object Undefined]"
Object.prototype.toString.call(myNull); // "[object Null]"
参考:https
:
//es5.github.io/x15.2.html#x15.2.4.2 https://es5.github.io/x9.html#x9.9
https://javascriptweblog.wordpress.com/ 2010/09/27 / the-secret-life-of-javascript-primitives /