jim dif
jim dif

Reputation: 641

Why does this javascript code using prototype work?

I have this javascript code below:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>

        <script>
            function Person(first, last) {
                this.first = first;
                this.last  = last;
            }

           Person.prototype.toString = function() { 
                return this.first + this.last;
           }
            var person = new Person("John", "Dough");

            alert(person); // same result since alert calls toString()  

        </script>
    </head>
    <body>
    </body>
</html>

The question is why does the alert(person) display "JohnDough"? To me, alert(person) should not display anything.

Upvotes: 0

Views: 77

Answers (2)

Ashley Sheridan
Ashley Sheridan

Reputation: 526

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.

Upvotes: 1

Ian
Ian

Reputation: 50905

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.

Upvotes: 5

Related Questions