function Chess(name, color, x, y) { //这里定义了一个名为Chess的构造函数
this.name = name
this.color = color
this.position = {}
this.position.x = x
this.position.y = y
this.move = function (x, y) {
console.log(this.color + this.name + '移动到了' + x + ',' + y);
this.position.x = x
this.position.y = y
}
}
let c = new Chess("棋", "黑", 10, 20)
c.move(50,100)
let b = new Chess("棋", "黑", 50, 100)
function isObjEqual(o1,o2){
let props1 = Object.getOwnPropertyNames(o1);
let props2 = Object.getOwnPropertyNames(o2);
if (props1.length !== props2.length) {
return false;
}
for (let i = 0,max = props1.length; i < max; i++) {
let propName = props1[i];
if (o1[propName] !==o2[propName]) {
return false;
}
}
return true;
}
console.log("比较bc:"+isObjEqual(b,c))
问题出现在position属性上,虽然他们的position属性值都是{x: 50, y:100},但只是长得一样的对象罢了,并不是同一个对象。这里应该判断数值的类型,如果是数组,对象之类的引用类型数据,还需要深度的进行判断
position是个对象,对象是引用类型数据,可以理解成postion就是个引用地址,虽然指向的数据是一样的,但是这个地址是不一样的