Reputation: 36189
Say I have
function Foo() {
// stuff
}
Foo.prototype.bar = function() {
return new Bar();
}
function Bar() {};
module.exports = Foo;
Now say I have
const foo = new Foo();
console.log(foo instanceof Foo); // true
const bar = new Foo().bar();
console.log(bar instanceof Foo); // false
console.log(bar instanceof Foo.prototype.bar); // false
Here Bar
is never exported. So how can I test if bar
is an instance of ... something? Can I somehow have bar instanceof Foo
or a subset of Foo or something?
Upvotes: 0
Views: 29
Reputation: 138257
You could compare the prototype of one bar to another:
Object.getPrototypeOf(bar) === Object.getPrototypeOf((new Foo).bar())
Upvotes: 0
Reputation: 115940
By default, the function Bar
is available as the constructor
on Bar.prototype
, which is in new Bar()
's prototype chain. (This is basically the only thing that constructor
is ever useful for in practice.)
bar instanceof new Foo().bar().constructor
Conversely, if you don't want to leak the Bar
constructor function in this fashion, you can clobber Bar.prototype.constructor
with a new value (or just delete
it) before your export Foo
. If constructor
has been cleared in this way, you can still check if an object's prototype chain includes the same prototype as a newly-created Bar
instance:
var barProto = Object.getPrototypeOf(new Foo().bar());
var isBar = barProto.isPrototypeOf(bar);
Upvotes: 1