【问题标题】:isPrototypeOf() usage when dealing with inheritance in JavaScript在 JavaScript 中处理继承时的 isPrototypeOf() 用法
【发布时间】: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


    【解决方案1】:
    1. isPrototypeOf 检查一个对象是否在另一个对象的原型链中,所以是的,它确实有多个级别

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

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

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

    【讨论】:

      【解决方案2】:

      isPrototypeOf() 方法测试另一个对象原型链中的对象

      在您的代码中

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

      打印为 true 因为 Square 方法在链中 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 并需要检查是否 Fi 的原型存在于 Fum 原型链中,你可以这样做 这个:

      var fum = new Fum();
      // ...
      
      if (Fi.prototype.isPrototypeOf(fum)) {
        // do something safe
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-07
        • 2014-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多