字符串不是对象,为什么它们有属性? [英] Strings are not object then why do they have properties?
问题描述
这样的代码:
var str = "Hello StackOverflow !";
alert(typeof str);
给我字符串
作为结果。这意味着字符串不是对象,那么为什么我们有字符串 str
的属性,如 str.substring
, str.indexOf等?
当我将属性设置为
gives me string
as result. This means strings are not objects, then why do we have properties of a string str
like str.substring
, str.indexOf etc.?
Also when i set property to it as
str.property =自定义属性已设置;
并尝试获取此警报(str.property)
,它给了我 undefined
。为什么?
str.property = "custom property is set";
and trying to get this alert(str.property)
, it gives me undefined
. Why?
推荐答案
像Hello这样的字符串不是JavaScript中的对象,但是在像
A string like "Hello" is not an object in JavaScript, but when used in an expression like
"Hello".indexOf(2)
从构造函数 String
派生的新对象包含字符串Hello
。并且 indexOf
是 String.prototype
的属性,所以事情按预期工作,即使有很多魔法on。
A new object derived from the constructor function String
is produced wrapping the string "Hello"
. And indexOf
is a property of String.prototype
so things work as expected, even though there is a lot of magic going on.
在以下情况中
> var s = "xyz"; s.prop = 1; console.log(s.prop);
undefined
您看到的原因 undefined
是:
- 变量
s
的值是一个原始字符串 - 在
s.prop = 1
中,名为prop
的属性是分配给一个新的匿名包装器对象。 - 在上面的第三个语句中,创建了另一个新对象来包装原语
s
。这与第二个语句中的包装器对象不同,并且它没有prop
属性,因此undefined
根据基本的JavaScript规则询问其值时生成。
- The variable
s
is given a value which is a primitive string - In
s.prop = 1
and property namedprop
is assigned to a new, anonymous wrapper object. - In the third statment above, another new object is created to wrap the primitive
s
. That is not the same wrapper object as in the second statement, and it does not have aprop
property, soundefined
is produced when asking for its value according to the basic JavaScript rules.
这篇关于字符串不是对象,为什么它们有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!