迷失了javascript中"constructor.name"的输出

Amo*_*rni 5 javascript string constructor javascript-objects

我有一个类似的条件来检查String类型构造函数名称是否是"String""string".

我迷失了以下JS代码的输出:

(typeof([].constructor.name)).constructor.name
"String"

typeof([].constructor.name).constructor.name
"string"
Run Code Online (Sandbox Code Playgroud)

但是,当我测试以下代码的输出时,我会更加困惑:

(typeof([].constructor.name))
"string"

typeof([].constructor.name)
"string"

"string".constructor.name
"String"
Run Code Online (Sandbox Code Playgroud)

根据我的理解,输出应始终为"String".

任何人都可以对我所缺少的内容或以上代码出错吗?

Mau*_*ppe 1

一个可能的原因

使用控制台后,我发现以下内容,看起来可能typeof(a).b相当于typeof (a).b,所以看起来以下内容是等价的

(typeof([].constructor.name)).constructor.name
(typeof [].constructor.name).constructor.name
Run Code Online (Sandbox Code Playgroud)

然而,对于第二个示例,似乎执行了以下操作

typeof([].constructor.name).constructor.name
typeof ([].constructor.name).constructor.name
Run Code Online (Sandbox Code Playgroud)

第一个示例中的第二个括号充当分组运算符,这可能是奇怪结果的原因

关于"string""String"

name您可能已经知道,我们可以通过属性访问命名函数的名称

function A(){}
A.name // A
Run Code Online (Sandbox Code Playgroud)

此外,当您在幕后创建函数时,会创建一个可通过函数的属性访问的对象,该对象通过其属性prototype引用函数本身 constructor

function A(){}
A.prototype  // {constructor: A}
A.prototype.constructor === A // true
Run Code Online (Sandbox Code Playgroud)

每当您创建函数的“实例”时,其隐藏[[Prototype]]属性(又名__proto__)都指向构造函数的原型,因此

[].__proto__ === Array.prototype // true
Run Code Online (Sandbox Code Playgroud)

由于空数组没有定义属性,因此 JS 会在上面看到的空数组所 constructor 指向的对象中查找具有属性的对象,因此__proto__Array.prototype constructor

[].constructor === Array // true
Run Code Online (Sandbox Code Playgroud)

从这里开始,操作数的解析变得微不足道

[].constructor.name // "Array"
[].constructor.name.constructor === String // true
[].constructor.name.constructor.name // "String", i.e. the name of the `function String() {}`
Run Code Online (Sandbox Code Playgroud)

所以在你的例子中

(typeof [].constructor.name).constructor.name
// evaluated to
(typeof "Array").constructor.name
// evaluated to
"string".constructor.name
// evaluated to
String.name
// evaluated to
"String"
Run Code Online (Sandbox Code Playgroud)

对于第二个例子

typeof ([].constructor.name).constructor.name
// evaluated to
typeof "String"
// evaluated to
"string"
Run Code Online (Sandbox Code Playgroud)

这个故事的寓意是:使用typeof operator而不是typeof()