1

As per my knowledge, the second case below should be true, but in fact it is false. So why is it not true?

Case 1

     var P = function(){};
         P.prototype.get = function(){};

    var p = new P,q = new P;        
    console.log(q.__proto__ === p.__proto__) //true

Case 2

var PP = function(){
    var P = function(){};
    P.prototype.get = function(){};
    return new P;
};

var p = PP(), q = PP();
console.log(q.__proto__ === p.__proto__) //false
1
  • Thanks Geeks, I found the mistake. Commented May 6, 2012 at 22:10

4 Answers 4

3

In the first case, P and get() are predefined globals. In the second, they're local to the function that defines PP, hence, a different reference for each instance.

Sign up to request clarification or add additional context in comments.

Comments

2

In the top one, you have a new P.

In the second, you have new P in the function and then take new of that function.

This might screw it up.

Nevermind, it's because of the global vars, like he said.

2 Comments

Extra new was my mistake (in 2 case). p and q objects are not equal even after removed the extra new
@Ganesh Kumar- If you remove the second new it checks out for me
2

When you call the PP function you create a new function object each time that is called P. Each one of those functions has a different prototype.

Comments

2

In the first case var p = new P,q = new P; both instantiated the global P and it's prototype so it returns true.

In the second case q and p are both different objects instantiated using new PP which returned different P from inside PP function using return new P. So it returns false.

3 Comments

Sorry, didn't get it, what you asked ?
I already read that book. small confusion with prototype stuff. Thanks
Yes, it's really sometimes confuses me too because it's really confusing, anyway.

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.