[英]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.