这个问题来 self 对一家本地公司的采访。我相信我的答案是正确的,但面试官却说不然。
问题:继承Parent对象Shape,创建一个名为Circle的对象,然后判断Circle实例变量是否等于父对象实例。
我回答“不,它们不相等”,但面试官说由于 Circle 继承自 Shape,因此它们是相等的。当时我很困惑。
我很好奇,只是编写了以下代码进行“相等”比较,看来我的答案是正确的。下面的代码来 self 自己:
//Parent Constructor
function Shape() {
//this.radius = r;
}
//Child Constructor using Shape's constructor
function Circle() {
Shape.call(this);
}
Circle.prototype = Object.create(Shape.prototype, {
constructor: {
value: Circle,
enumerable: true,
configurable: true,
writable: true
}
});
var myCircle = new Circle(5); // Child instance
var myShape = new Shape(5); // Parent instance
console.log(myShape == myCircle); // check for equality - result is '**false**'
最佳答案
您无法使用 ==
比较不同的对象实例,因为它们在内存中具有不同的地址。这适用于大多数 OOP 语言。
在 Javascript 中,它们可以被认为是相等的,因为 Shape 和 Circle 显然具有相同的属性。因此深度比较将返回 true。
关于JavaScript:比较子实例及其父对象实例是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27452864/