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

前端 未结 6 796
梦毁少年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:09

    The problem is that all of your classes you reference are descendants of Foo. Such that new Baz() instanceOf Bar && new Bar() instanceOf Foo === true. So when you ask is Bar instanceOf Foo, it will be true through inheritance.

    Due to there being no Java getClass() equivalent in JS, you should use something like:

    if (value.constructor.name !== Foo.name)
    

提交回复
热议问题