Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - Strings are not object then why do they have properties?

Code like this:

var str = "Hello StackOverflow !";
alert(typeof str);

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 = "custom property is set"; and trying to get this alert(str.property), it gives me undefined. Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A string like "Hello" is not an object in JavaScript, but when used in an expression like

"Hello".indexOf(2)

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.

In the following case

> var s = "xyz"; s.prop = 1; console.log(s.prop);
undefined

The reason you see undefined is that:

  1. The variable s is given a value which is a primitive string
  2. In s.prop = 1 and property named prop is assigned to a new, anonymous wrapper object.
  3. 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 a prop property, so undefined is produced when asking for its value according to the basic JavaScript rules.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...