String是String()对象的一个实例吗?
String是String()对象的一个实例吗?
这个问题在这里已经有答案:
我目前正在学习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日
String.length不是来自String.prototype的方法。
length
是String的一个属性。
回答你的问题,"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