为什么这个使用原型的javascript代码有效? [英] Why does this javascript code using prototype work?

查看:44
本文介绍了为什么这个使用原型的javascript代码有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有这个 javascript 代码:

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>

问题是为什么 alert(person) 显示JohnDough"?对我来说,alert(person) 不应该显示任何内容.

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

推荐答案

当使用 alert 时,该方法会隐式地尝试调用对象上的 toString.在您的情况下,toString 已定义并执行您在显式调用 toString 时所期望的操作.如果您没有定义 toStringalert 将使用 Object 的本机 toString 方法并返回"[object Object]",正如@FelixKling 指出的那样.

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.

这篇关于为什么这个使用原型的javascript代码有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆