2

I am trying to use OOPs in javascript. What i am trying is,

I have 2 classes say classA and classB. I am inheriting classA in classB. Like :

 function classA(){
    this.propA = "somevalue of A";
 }

 function classB(){
    classB.prototype = new classA();              //inheriting
    classB.prototype.constructor = classB;        //updating constructor defination
    this.propB = "somevalue of B";
 }

Now i created the object of classB :

var classBObject = new classB();

and than trying to access base class property value with :

alert(classBObject.propA);      //here i am expecting "somevalue of A"

but the alert shows me empty. Can anybody please tell me what i am doing wrong here ?

1
  • Javascript is a prototype-based language, not a class-based language. So, technically there are no classes. In Javascript, objects inherit directly from other objects, unlike in other class-based languages, where objects inherit from classes. There are 5 types in Javascript: String, Number, Boolean, Undefined, and Null. Everything else is an object. Commented Feb 14, 2013 at 8:19

1 Answer 1

3

Move the prototype assignment of classB outside the constructor:

function classA(){
    this.propA = "somevalue of A";
 }

 function classB(){
    // classB.prototype.constructor = classB;
    // ^ no need for this, constructor will be overwritten
    //   by classB.prototype = new classA
    this.propB = "somevalue of B";
 }

 classB.prototype = new classA; // assing prototype for classB here
Sign up to request clarification or add additional context in comments.

Comments

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.