String是String()对象的一个实例吗?

16 浏览
0 Comments

String是String()对象的一个实例吗?

这个问题在这里已经有答案

什么是JavaScript中字符串原型(primitives)和字符串对象(String objects)的区别?

为什么某些字面量(literals)的 instanceof 返回false?

我目前正在学习JavaScript,有些东西我不太理解。

//This means that I am using a method from the String.prototype
"ThisIsMyString".length

因此,如果我使用(\"ThisIsMyString\" instanceof String)应该会返回true,不是吗?但事实证明返回false...我认为这是因为原型类型(primitive type)。

这里是我的问题: 如果\"ThisIsMyString\"不是String的实例,它如何访问该对象的属性?我不知道其中的哪一部分。

admin 更改状态以发布 2023年5月21日
0
0 Comments

你可以使用这些方法,因为语言会识别和转换基本类型为 String 对象的临时实例,并返回该对象的 length 属性。

0
0 Comments

String.length不是来自String.prototype的方法。

length是String的一个属性。

请参考MDN的String.length文档。


回答你的问题,"hello" instanceof String返回false的原因在于instanceof的实际工作方式。

Object.getPrototypeOf("hello")
// TypeError: Object.getPrototypeOf called on non-object

然而,这是你的字符串文本如何访问这些方法/属性的方式。

"my string".constructor === String
// true
"my string".__proto__ === String.prototype
// true

如果你想要一个真正的String实例

var str = new String("hello");
str instanceof String
// true

0