What does 'is an instance of' mean in Javascript?

后端 未结 7 784
面向向阳花
面向向阳花 2020-12-18 00:42

The answer to this question: What is the initial value of a JavaScript function's prototype property?

has this sentence:

The initial value

相关标签:
7条回答
  • 2020-12-18 01:21

    You're right that JavaScript doesn't have classes (yet), but it does have constructor functions, an instanceof operator that defines a relationship between objects and constructors, and a form of inheritance based on prototype chains.

    obj instanceof ctor is true when ctor.prototype is on obj's prototype chain.

    Modulo the caveat below, you could implement instanceof in EcmaScript 5 thus

    function isInstanceOf(obj, ctor) {
      var proto = ctor.prototype;
      if (typeof obj === "object" || typeof obj === "function") {
        while (obj) {
          if (obj === proto) { return true; }
          obj = Object.getPrototypeOf(obj);
        }
      }
      return false;
    }
    

    Unless you go around reassigning prototypes (o = new MyConstructor(); MyConstructor.prototype = somethingElse) it should be the case that new MyConstructor() instanceof MyConstructor.

    Section 15.3.5.3 explains this in detail.

    15.3.5.3 [[HasInstance]] (V)

    Assume F is a Function object.

    When the [[HasInstance]] internal method of F is called with value V, the following steps are taken:

    1. If V is not an object, return false.

    2. Let O be the result of calling the [[Get]] internal method of F with property name "prototype".

    3. If Type(O) is not Object, throw a TypeError exception.

    4. Repeat

      1. Let V be the value of the [[Prototype]] internal property of V.
      2. If V is null, return false.
      3. If O and V refer to the same object, return true.

    This isn't the whole story because host objects (like DOM nodes) are allowed to implement the [[HasInstance]] internal method however they like but most browsers implement host objects to behave as closely to native objects as possible.

    0 讨论(0)
提交回复
热议问题