为什么console.dir('')打印“没有属性”? [英] Why does console.dir('') print "no properties"?
问题描述
我认为字符串具有属性,例如匹配
。为什么 console.dir('')
声称''
没有属性(至少在Google Chrome中)?
I was under the impression that strings have properties, such as match
. Why does console.dir('')
claim that ''
has no properties (at least in Google Chrome)?
推荐答案
这是因为''
是字符串文字,而不是实例字符串
class。由于匹配
等属性在 String.prototype
上声明,因此在使用字符串文字时不会看到它们。如果您使用 new
运算符,您将看到您的预期:
It's because ''
is a string literal, not an instance of the String
"class". As properties like match
are declared on String.prototype
, you won't see them when using a string literal. If you use the new
operator you will see what you expected:
var s = new String("hello");
console.dir(s);
这是Chrome开发者工具的截图(注意需要扩展原型
,因为您期望看到的方法是在原型上声明的,而不是 String
对象本身):
Here's a screenshot from Chrome's developer tools (notice the need to expand the prototype
, as the method you're expecting to see is declared on the prototype, not the String
object itself):
这篇关于为什么console.dir('')打印“没有属性”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!