0

I'm trying out instanceof operator. I tried out something like this.

function f(){ return f; }
new f() instanceof f;
// false

Why this came out to be false, when these are true

function f(){ return f; }
new f() instanceof Function; 
// true

function f(){ return f; }
new f() instanceof Object;
//true

When tried to save this to a variable still resulted same

function f(){ return f; }
var n = new f();

n instanceof f;
// false

n();
// function f()

n() instanceof f;
// false

n instanceof Function     // true
n() instanceof Function   // true

Why return f; statement have changed everything? What did return f did to cause this behavior?

NAVIN
  • 3,193
  • 4
  • 19
  • 32

3 Answers3

6

First, I'd recommend checking out the article on the new operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Specifically, note that

When the code new Foo(...) is executed, the following things happen:

  1. A new object is created, inheriting from Foo.prototype.
  2. The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

By explicitly returning f, your are overriding the normal creation process. When you use instanceof, you are asking "Is n and instance of f". It's not. It is f. It is not an instance of itself.

Since clearly f is a function, and n === f, both will return true when you try to determine if they are functions. Additionally, in Javascript, functions themselves are objects (as are arrays), which is why new f() instanceof Object is true.

Community
  • 1
  • 1
rfestag
  • 1,913
  • 10
  • 20
3

You are returning f from your constructor. f is the constructor. So your constructor is never constructing an instance, you're just always testing whether the constructor is an instance of itself. Which it isn't, by definition.

deceze
  • 510,633
  • 85
  • 743
  • 889
2

By returning f, you return the function, which is no instance of f, because it lacks the call with new.

function f() { return f; }
console.log(new f() === f);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392