instanceof 含义

看到一个问题:

把一个字面量对象,变成某个类的实例

function Type() {}
var a = {};
______________ 
// a instanceof Type === true

查了一下instanceof 的执行过程,大概如下

function instance_of(V, F) {
  var O = F.prototype;
  V = V.__proto__;
  while (true) {
    if (V === null)
      return false;
    if (O === V)
      return true;
    V = V.__proto__;
  }
}
// This is basically paraphrasing ECMA-262 edition 5.1 (also known as ES5), section 15.3.5.3.

所以我们要做的就是把Type的原型成为a的原型链上的一个节点,简单起见直接设成a的构造器的原型

a.__proto__ = Type.prototype
// a instanceof Type === true
原文地址:https://www.cnblogs.com/chocking/p/4742185.html