Home  >  Q&A  >  body text

javascript - instanceof operator

https://www.ibm.com/developer...

According to this article

instaceof can be simulated with the following code

function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
  var O = R.prototype;// 取 R 的显示原型
  L = L.__proto__;// 取 L 的隐式原型
  while (true) { 
    if (L === null) 
      return false; 
    if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
      return true; 
    L = L.__proto__; 
  } 
 }
     

But
var a=1;
instance_of(a,Object) is true
a instanceof Object returns false, why is this?

黄舟黄舟2697 days ago679

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:28:43

    Owner, you can try your instance_of 是代替不了 instanceof’s

    First, make sure that your sample a is of type Number

    However, the execution result is as follows
    instance_of(a, Object) // true
    instance_of(a, Number) // true

    Modify instance_of method:

    function instance_of(L, R) {
      try {
        var O = R.prototype;// 取 R 的显示原型
        L = Object.getPrototypeOf(L);// 取 L 的隐式原型
        while (true) { 
          if (L === null) 
            return false; 
          if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
            return true; 
          L = L.Object.getPrototypeOf(L); 
        }
      } catch (e) {
        return false
      }
    }

    Experiment again:

    var a = 1
    
    instance_of(a, Object) // false 
    instance_of(a, Number) // true
    
    var parent = function () {}  
    var child = new parent()
    
    instance_of(child, parent) // true

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:28:43

    The standard used in this article is ES3

    ES6’s instanceof标准更长一点, 规定了当type(L)不是Object时L instanceof R should return false. This mock code does not apply

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:28:43

    One part is the content of the prototype chain, in your simulation code:

        function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
          var O = R.prototype;// 取 R 的显示原型
          L = L.__proto__;// 取 L 的隐式原型
          while (true) { 
            if (L === null) 
              return false; 
            if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
              return true; 
              L = L.__proto__; 
           } 
         }

    L = L._proto_ 代表着L会沿着原型链一直向上查找原型,而在本例中,最后是从Number包装对象==>Object对象,而R就是Object,再经过全等运算符之后就返回true,所以instance_of(a,Object) is true.

    a instanceof ObjectReturns false because it does not go through the prototype chain search, it is directly judged between the instance of the Number object and the Object, so the result is false

    reply
    0
  • Cancelreply