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
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.
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.
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.
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.