0

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?

1
  • @apsillers yes good catch. Fixed it! Commented Dec 5, 2017 at 19:54

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

You could compare the prototype of one bar to another:

 Object.getPrototypeOf(bar) === Object.getPrototypeOf((new Foo).bar())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.