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

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

    You should test if value's internal [[Prototype]] is exactly Foo.prototype. You can get the internal [[Prototype]] with Object.getPrototypeOf :

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

提交回复
热议问题