繁体   English   中英

此JavaScript代码有什么问题?

[英]What's wrong with this javascript code?

<html>
<head>

    <script type="text/javascript">

    function Person (name, age) {
        this.name = name;
        this.age = age;
        this.sayName = function () {
            alert(this.name);
        }
    }    
    var person1 = new Person ("tom", 29);
    var person2 = new Person ("frank", 21);
    alert(person1.sayName==person2.sayName);

    </script>
</head>

<body>
</body>
</html>

您正在比较功能拼写者,而不是结果。

尝试:

alert( person1.sayName() == person2.sayName() );

但是再说一次:您的sayName()会触发另一个alert()。 这段代码是关于什么的?

没什么问题(除了第6行上略显古怪的分号缺失)。

因为sayName函数是在构造函数内部创建的,所以每次创建新对象时都会创建一个新函数。 (因此功能不同,并且==返回false)

人们通过将函数附加到原型对象上来解决此问题:

function Person (name, age) {
    this.name = name;
    this.age = age;
}    

Person.prototype.sayName = function () {
    alert(this.name);
};

var person1 = new Person ("tom", 29);
var person2 = new Person ("frank", 21);
alert(person1.sayName==person2.sayName);

这将仅创建一个功能(节省您的内存),并且警报将显示“ true”。

person1person2是不同的对象,因此它们的比较应该false

但是,您可能打算按字面意义比较这些函数,可以使用toString() ,在这种情况下,警报为true

jsFiddle

当然,它们都具有不同的this.name因此,如果确实返回了该名称,并且您调用了函数并进行了比较,那么它也是false

暂无
暂无

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

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