0

I'm new for OOPS JavaScript. Be clear. See my JavaScript code here,

function a(){
    this.first = "Kar";
}
function b(){
    this.last = "Sho";
}
function c(){
    this.getName = function(){
        return this.first+this.last;
    }
}

c.prototype.u = new a();
c.prototype.v = new b();

var d = new c();

alert(d.getName());

Here, I'm getting following output,

NaN

But I want to print KarSho. Where is problem?

I know following method,

b.prototype = new a();
c.prototype = new b();

Actually what I want is, just call a and b in c. That's it.

2 Answers 2

2

Call both a and b in the c constructor.

function a(){
    this.first = "Kar";
}
function b(){
    this.last = "Sho";
}
function c(){
    a.call(this);
    b.call(this);
    this.getName = function(){
        return this.first+this.last;
    }
}

var d = new c();

alert(d.getName());

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

Comments

1
c.prototype.u = new a();
c.prototype.v = new b();

Creates instances of the a and b object on the c.v and c.u prototype properties.

To access them, you would call them by:

function c(){
  this.getName = function(){
    return this.v.first + this.u.last;
  }
}

This is not really inheritance, but rather assigning of properties.

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.