//I have this base Rectangle constructor function
function Rectangle (length, width){
    this.length = length;
    this.width = width;
}

Rectangle.prototype.getArea = function (){
    return this.length * this.width;
};

//Creating Square constructor function that will inherit from Rectangle...

function Square(size){
    this.length = size;
    this.width  = size;
}

Square.prototype = new Rectangle();
Square.prototype.constructor = Square;

//creating rectangle and square instances
var rect = new Rectangle(5, 10);
var square = new Square(6);

console.log(rect.getArea());  //50
console.log(square.getArea());  //36

console.log(Rectangle.prototype.isPrototypeOf(Square.prototype)); //true

console.log(Rectangle.prototype.isPrototypeOf(rect)); //true

console.log(Square.prototype.isPrototypeOf(square));  //true


我的问题是当我执行下面的console.log()时,我希望它可以打印false。但是,我得到了true

console.log(Rectangle.prototype.isPrototypeOf(square));  //true


1)这是否意味着isPrototypeOf进入多个级别?

2)如果isPrototypeOf进入多个级别,使用isPrototypeOf而不是instanceof有什么意义?

我已经阅读过Why do we need the isPrototypeOf at all?,但不了解它在我的用例中如何应用。

最佳答案

isPrototypeOf检查一个对象是否在另一个对象的原型链中,因此是的,它确实可以进入多个级别


https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf


它们可以用于相同的目的。您可以执行square instanceof SquareSquare.prototype.isPrototypeOf(square),但是如您所见,instanceof具有将对象与其构造函数匹配的特定目的,其中isPrototypeOf可以更广泛地用于检查任何对象是否在另一个对象的原型链中。


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

10-01 00:24