Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  171] [ 1]  / answers: 1 / hits: 16377  / 15 Years ago, tue, january 12, 2010, 12:00:00

I've been messing around with the ECMA-262 standard (ECMAScript Language Specification, 3rd edition, if it matters for this - I have not found any difference between the 3rd and 5th edition on String Type / String Object).



There's one thing that baffles me: the difference between the String Type and the String Object. Yes I know the difference in the sense that the String Type is a sequence of 16-bit UTF-16 units and the String Object is a built-in object with its internal Class property set to String and its internal Value property set to a value of the String Type.



But reading the specification, the string type does not seem to expose any methods; that is, it's just a value without any additional properties. Take this code, everything is exactly as expected:



document.writeln(typeof foo); // 'string'
document.writeln(typeof new String(foo)); // 'object'


The first type is the actual String Type and the second is the Object Type (it's an object of class String, but its data type is object). However, looking at this:



foo.charAt(0);

fooStrObj = new String(Foo);
fooStrObj.charAt(0);


They both seem to expose the same functions, but there are no functions on the String Type defined in the ECMA-262 standard; all the functions it exposes are from the String.prototype object (and I can see no reference to the fact that the String Type magically exposes all the properties and functions of the String.prototype object in the ECMA-262 standard). So are the values of type String Type automatically promoted to a String Object with the original String Type value as its internal Value property?



And if they are treated exactly the same (which for all intents and purposes they seem to be), why have two different ways to represent a String?


More From » javascript

 Answers
14

Strings are a value type in JS, so they can't have any properties attached to them, no prototype, etc. Any attempt to access a property on them is technically performing the JS [[ToObject]] conversion (in essence new String).



Easy way of distinguishing the difference is (in a browser)



a = foo
a.b = bar
alert(a.b = + a.b); //Undefined

A = new String(foo);
A.b = bar;
alert(A.b = + A.b); // bar


Additionally while



foo == new String(foo)


is true, it is only true due to the implicit type conversions of the == operator



foo === new String(foo)


will fail.


[#97851] Sunday, January 10, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sashacitlallik

Total Points: 30
Total Questions: 100
Total Answers: 85

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;