1

Take a look at this code:

function Foo () {
    console.log(this instanceof Foo);
    return { name: "nitesh" }; 
}

foo = new Foo(); //true 
console.log(foo instanceof Foo) //false
  1. Why is foo not an instance of Foo?
  2. Why is this an instance of Foo?
1
  • 2
    You are basically doing { name: "nitesh" } instanceof Foo. Commented Aug 9, 2012 at 14:20

1 Answer 1

11

In your Foo function, you are returning an object. This is what foo gets set to. That is not a Foo object, it's just a "normal" object.

Try it this way:

function Foo(){
    console.log(this instanceof Foo);
    this.name = "nitesh";
}

var foo = new Foo(); //true 
console.log(foo instanceof Foo) //true
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for explanation yet i am still confused how come is this an instance of Foo?
@niteshsharma: That's how new works. From the docs: The constructor function is called with the specified arguments and 'this' bound to the newly created object.

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.