Reputation: 339
<script>
function ClassA()
{
this.a=function(){alert();};
}
function ClassB()
{
this.b=function(){alert();};
}
ClassB.prototype=new ClassA();
var objB1=new ClassB();
var objB2=new ClassB();
alert(objB1.a==objB2.a);
alert(objB1.b==objB2.b);
</script>
Why the first alert is true and the second is false? Thanks
Upvotes: -1
Views: 72
Reputation: 60414
Upvoted @maerics's (good) answer, but want to point out something that might not be obvious. Inside of a (constructor) function, this
refers to the new instance being created. So, each time new ClassA
or new ClassB
is invoked, a new instance is created and this.a
or this.b
refers to a new function assigned to a property of the newly instantiated object.
So, looking at your code, a simple question to ask yourself is: "How many new instances of each type are being created?"
I see just one occurrence of new ClassA()
, which means just one instance of ClassA
is created, therefore, only one function is assigned to this.a
. But, I see two occurrences of new ClassB()
, therefore, two new functions are created, one for each instance.
Upvotes: 0
Reputation: 156364
Because the attribute "a" is not a direct property of instances of ClassB (that is, objB1.hasOwnProperty("a") is false) the property is read from its prototype. Since there is just one prototype object for all instances of ClassB, objB1.a and objB2.a are literally referring to the same function, defined in their common prototype object. (You can verify that objB1.a===objB2.a
).
But the attribute "b" is defined as a new function for each and every instance of ClassB and separate function instances are not equal to each other.
Upvotes: 2