1

I'm learning javscript and trying to know more about object oriented programming.

i have a class called man:

var man = function() {

    this.name = "jack";

    this.walk = function(){
        console.log("im walking");
    };

};

i want create another class called hero that inherits from man containing all man class methods and properties

var hero = function(){

 // inherit from man and has it own methods

};

How to do that so i can create object contain methods from both of them.

Sky Walker
  • 978
  • 1
  • 9
  • 22

1 Answers1

0

After (and outside of) the hero function assign new man() to hero's prototype:

var man = function() {

    this.name = "jack";

    this.walk = function() {
        console.log("im walking");
    };
};

var hero = function() {
    // hero stuff
}

hero.prototype = new man();

// ...

var batman = new hero();

alert(batman.name) // jack
DonovanM
  • 1,174
  • 1
  • 12
  • 17
  • 1
    No, [don't use `new man()` for creating the prototype](https://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here)! – Bergi Mar 21 '15 at 20:06
  • i think var hero = function() { man.call(this) } was the right answer why you change it ? – Sky Walker Mar 22 '15 at 15:33