Skip to content Skip to sidebar Skip to footer

Why Does This Javascript Code Using Prototype Work?

I have this javascript code below:

Solution 1:

When using alert, the method implicitly attempts to call a toString on the object. In your case, toString is defined and does what you expect when explicitly calling toString. If you hadn't defined toString, alert would have used the native toString method of an Object and returned "[object Object]", as pointed out by @FelixKling.

Solution 2:

It's because that object has a toString() method. alert() requires a string, and will use this method for an object if it exists, or its own built-in one if not. As the method here returns the forename and surname, that's what you get in the alert() dialogue.

Post a Comment for "Why Does This Javascript Code Using Prototype Work?"