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.
When using
alert, the method implicitly attempts to call atoStringon the object. In your case,toStringis defined and does what you expect when explicitly callingtoString. If you hadn’t definedtoString,alertwould have used the nativetoStringmethod of anObjectand returned “[object Object]”, as pointed out by @FelixKling.