简体   繁体   English

为什么使用原型的此javascript代码有效?

[英]Why does this javascript code using prototype work?

I have this javascript code below: 我下面有这个JavaScript代码:

<!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"? 问题是为什么alert(person)显示“ JohnDough”? To me, alert(person) should not display anything. 对我而言, alert(person)不应该显示任何内容。

When using alert , the method implicitly attempts to call a toString on the object. 使用alert ,该方法隐式尝试在对象上调用toString In your case, toString is defined and does what you expect when explicitly calling toString . 在您的情况下,定义了toString并执行显式调用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. 如果尚未定义toString ,则alert将使用Object的本机toString方法并返回@FelixKling指出的“ [object Object]”。

It's because that object has a toString() method. 这是因为该对象具有toString()方法。 alert() requires a string, and will use this method for an object if it exists, or its own built-in one if not. alert()需要一个字符串,如果存在则将对对象使用此方法,否则将对它自己的内置对象使用此方法。 As the method here returns the forename and surname, that's what you get in the alert() dialogue. 当这里的方法返回名字和姓氏时,这就是您在alert()对话框中看到的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM