Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用equals和compareTo方法在Javascript中进行对象比较_Javascript - Fatal编程技术网

使用equals和compareTo方法在Javascript中进行对象比较

使用equals和compareTo方法在Javascript中进行对象比较,javascript,Javascript,我正在尝试使用equals和compareTo方法实现自定义相等和关系操作。然而,我得到了错误的结果。请帮我找出我做错的地方 var Person = function () { this.age = null; this.name = null; }; Person.prototype.equals = function (that) { if (this.age === that.age) return true; else return false; }; Pe

我正在尝试使用equals和compareTo方法实现自定义相等和关系操作。然而,我得到了错误的结果。请帮我找出我做错的地方

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

Person.prototype.equals = function (that) {
    if (this.age === that.age) return true;
    else return false;
    };

Person.prototype.compareTo = function (that) {
    return this.age - that.age;
    };

var p1 = new Person();
var p2 = new Person();

p1.age = 10;
p2.age = 20;

document.writeln(p1 < p2); // this should be true but evaluates to false.
var Person=函数(){
this.age=null;
this.name=null;
};
Person.prototype.equals=函数(即){
如果(this.age==that.age)返回true;
否则返回false;
};
Person.prototype.compareTo=函数(即){
返回this.age-that.age;
};
var p1=新人();
var p2=新人();
p1.年龄=10岁;
p2.年龄=20岁;
文件写入(p1
JavaScript没有运算符重载,并且
不会调用对象上的任何方法,因此
p1
不会使用
equals
compareTo

要进行比较,您可以使用:

document.writeln(p1.compareTo(p2) < 0);