[英]isPrototypeOf() usage when dealing with inheritance in JavaScript
//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
什么意义?
我读过这个为什么我们需要isPrototypeOf呢? 但不明白它在我的用例中是如何应用的。
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf
square instanceof Square
或Square.prototype.isPrototypeOf(square)
square instanceof Square
但正如您所看到的, instanceof
具有将对象与其构造函数匹配的特定目的,其中isPrototypeOf可以更广泛地用于检查是否有任何对象在原型链中另一个 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
isPrototypeOf()
方法测试另一个对象的原型链中的对象
在您的代码中
console.log(Rectangle.prototype.isPrototypeOf(square)); // true
它打印为true,因为Square Method位于getArea方法的链中,而getArea是Rectangle的原型方法
Rectangle.prototype.getArea = function (){
return this.length * this.width;
};
例如根据Mozilla Docs
function Fee() {
// ...
}
function Fi() {
// ...
}
Fi.prototype = new Fee();
function Fo() {
// ...
}
Fo.prototype = new Fi();
function Fum() {
// ...
}
Fum.prototype = new Fo()
稍后,如果您实例化Fum并需要检查Fum原型链中是否存在Fi的原型,您可以这样做:
var fum = new Fum();
// ...
if (Fi.prototype.isPrototypeOf(fum)) {
// do something safe
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.