When is it safe to use .toString()?
-
20-08-2019 - |
Question
Doesn't value have to return toString() to be able to call value.toString()? When do you know you can call value.toString()?
<script>
var newList = function(val, lst)
{
return {
value: val,
tail: lst,
toString: function()
{
var result = this.value.toString();
if (this.tail != null)
result += "; " + this.tail.toString();
return result;
},
append: function(val)
{
if (this.tail == null)
this.tail = newList(val, null);
else
this.tail.append(val);
}
};
}
var list = newList("abc", null); // a string
list.append(3.14); // a floating-point number
list.append([1, 2, 3]); // an array
document.write(list.toString());
</script>
OTHER TIPS
As Mr. Shiny and New states, all JavaScript objects have a toString
method. However, that method is not always useful, especially for custom classes and object literals, which tend to return strings like "[Object object]"
.
You can create your own toString
methods by adding a function with that name to your class' prototype, like so:
function List(val, list) {
this.val = val;
this.list = list;
// ...
}
List.prototype = {
toString: function() {
return "newList(" + this.val + ", " + this.list + ")";
}
};
Now, if you create a new List(...)
and call its toString
method (or run it through any function or operator that converts it to a string implicitly), your custom toString
method will be used.
Finally, to detect whether an object has a toString
method defined for its class (note that this will not work with subclassing or object literals; that is left as an exercise for the reader), you can access its constructor
's prototype
property:
if (value.constructor.prototype.hasOwnProperty("toString")) {
alert("Value has a custom toString!");
}
document.write, like window.alert, calls its argument's toString method before it writes or returns anything.
Other answers are correct that toString
exists on all Javascript objects.
In general, though, if you want to know if a function exists on your object, you can test it like so:
if (obj.myMethod) {
obj.myMethod();
}
This does not, of course, ensure that myMethod
is a function instead of a property. But presumably you'll know that.