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

asked Mar 23, 2011 at 1:07

2 Answers 2

2

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.

answered Mar 23, 2011 at 1:16
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Mar 23, 2011 at 2:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.