What's the difference between isPrototypeOf and instanceof in Javascript?

后端 未结 3 1460
梦毁少年i
梦毁少年i 2021-01-30 13:02

In some of my own older code, I use the following:

Object.prototype.instanceOf = function( iface )
{
 return iface.prototype.isPrototypeOf( this );
};

3条回答
  •  一整个雨季
    2021-01-30 13:37

    Operator precedence and truthiness differ since one is an expression and the other is a method call. One thing to emphasize is that both traverse the prototype chain, so you cannot assume that there is a one-to-one mapping between a matching prototype and the object in question:

    var i = 0;
    
    function foo()
    {
    console.log("foo");
    console.log(i++ + ": " + Object.prototype.isPrototypeOf(Object) ) //true
    console.log(i++ + ": " + Function.prototype.isPrototypeOf(Function) ) //true
    
    console.log(i++ + ": " + Function.prototype.isPrototypeOf(Function) ) //true
    console.log(i++ + ": " + Function.prototype.isPrototypeOf(Object) ) //true
    
    console.log(i++ + ": " + RegExp.prototype.isPrototypeOf( RegExp(/foo/) ) ) //true
    console.log(i++ + ": " + Object.prototype.isPrototypeOf( RegExp(/foo/) ) ) //true
    console.log(i++ + ": " + Function.prototype.isPrototypeOf( RegExp(/foo/) ) ) //false
    console.log(i++ + ": " + Object.prototype.isPrototypeOf(Math) ) //true
    console.log(i++ + ": " + Math.isPrototypeOf(Math) ) //false
    }
    
    function bar()
    {
    console.log("bar");
    console.log(i++ + ": " + (Object instanceof Object) ) //true
    
    console.log(i++ + ": " + (Function instanceof Function) ) //true
    console.log(i++ + ": " + (Function instanceof Object) ) //true
    
    console.log(i++ + ": " + (RegExp(/foo/) instanceof RegExp) ) //true
    console.log(i++ + ": " + (RegExp(/foo/) instanceof Object)  ) //true
    console.log(i++ + ": " + (RegExp(/foo/) instanceof Function) ) //false
    console.log(i++ + ": " + (Math instanceof Object) ) //true
    console.log(i++ + ": " + (Math instanceof Math) ) //error
    }
    try
      {
      foo()
      }
    catch(e)
      {
      console.log(JSON.stringify(e));
      }
    finally
      {
      try
        {
        bar();
        }
      catch(e)
        {
        console.log(JSON.stringify(e));
        }
      }

    References

    • Classes in ECMAScript 6 (final semantics)

提交回复
热议问题