Reading through Datatypes and conversion, I came across different methods to converting data into “string”.
by using the toString() method
by using the String() function
converting to a string using empty string concatenation :- x + “”;
My questions are :
a) which of the three is the preferable method?
b)Why?
c) Are there any specific instances when one is preferred over the other?
d) if so, would anybody be kind enough to illustrate it to me.
I seek your wisdom on this matter since I cannot help wonder whay there are so many different methods to achieve the same result.
I thank you all.
P.S. My textbooks are Mr. Colin Moock’s two books and I cannot find the explanation in there…
That won’t covert the data to the correct type but rather have the compiler explode in your face when you try and reference data of an incorrect type (which, don’t get me wrong, isn’t a bad thing).
toString is given to all objects automatically. Calls to the String function (type casting) and String.concat (with non-String objects) simply call the *toString *method of the instance. All in all, the three different ways are exactly the same in that the all ultimately call the toString method.
The only important thing to note is that the toString method can be overwritten:
[LIST=1]
[]In the prototype of the class governing the object which will affect all instances of that class.
[]As a property directly of the instance, which will only affect that instance.[/LIST]Thus modifying the return values of the String function and* String.concat*.
Thanks V2ikematu - yes Moock’s are interestingly written, TheCanadian and Defective for sharing your thoughts.
When I tried the above code, the trace() command returned the following error:
Error Scene=Scene 1, layer=Layer 1, frame=1:Line 2: Type mismatch in assignment statement: found String where Number is required.
var numberVar:Number = stringVar;
Total ActionScript Errors: 1 Reported Errors: 1
That’s what I mean by compiler exploding in your face. Like I said, giving variables a strict data type won’t convert data to the correct type but rather tell you when you try and reference the wrong type - by giving you an error - and that is where you use type casting to make it the correct type
Yes, I am beginning to understand how the interpreter works now. Since I last posted here, I have read on and found that Mr. Moock touches upon the subject once again in later chapters.
toString() is more flexible. I have tried out various combinations and I am getting the picture gradually, as they say.
Thank you TheCanadian. Let me also add that I have seen some of your creations posted on the web and have appreciated them very much.