【发布时间】:2016-04-20 05:51:32
【问题描述】:
//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?,但不明白它如何应用于我的用例。
【问题讨论】:
标签: javascript inheritance prototype