Check if object is a 'direct instance' of a class

前端 未结 6 797
梦毁少年i
梦毁少年i 2021-01-04 13:26

I have two classes:

class Bar extends Foo { // Foo isn\'t relevant
  constructor(value) {
    if (!(value instanceof Foo)) throw \"InvalidArgumentException:          


        
6条回答
  •  独厮守ぢ
    2021-01-04 14:00

    Check the constructor:

    if (!value || value.constructor !== Foo)
      throw 'InvalidArgumentException: (...)';
    

    or the prototype of the object (this is more similar to what instanceof does):

    if (!value || Object.getPrototypeOf(value) !== Foo.prototype)
      throw 'InvalidArgumentException: (...)';
    

提交回复
热议问题