Question

Why doesn't jordan have the properties of the Human class? Shouldn't saying Coder.prototype = new Human; be enough for all Coder classes to inherit all properties of the Human class?

Does it have something to do with defining functions as assignments?

var Human = function() {
     var hi = function() {
         alert('hi');
      };
     return {
        name : 'dan',
       sayHi : hi
     };
};

var dan = new Human();

var Coder = function() {
   var code = function() {
      alert('1010101');
   };    
  return {
    code : code
  };
};

Coder.prototype = new Human;
Coder.prototype.constructor = new Coder;
var jordan = new Coder();
console.log(jordan);
Was it helpful?

Solution 2

It's a funny thing: a JS constructor can return an object that becomes this. This object however doesn't follow the prototypes, as defined for the constructor (in this case it's a plain Object). The correct way that looks like your code would be:

var Human = function() {
    var hi = function() {
        alert('hi');
    };
    this.name = "dan";
    this.sayHi = hi;
};

// or even:
var Human = function() {
    this.name = "dan";
};

Human.prototype.sayHi = function() {
    alert('hi');
};

Similar for Coder. The inheritance code is OK.

OTHER TIPS

Your constructors do not return the objects they're creating, so inheritance won't work. Use this instead:

var Human = function() {
     this.sayHi = function() {
         alert('hi');
     };
     this.name = 'dan';
};

var dan = new Human();

var Coder = function() {
   this.code = function() {
      alert('1010101');
   };    
};

Coder.prototype = new Human;
Coder.prototype.constructor = Coder;
var jordan = new Coder();
console.log(jordan);

Another option, moving the stuff from Human to the prototype:

var Human = function() {};
Human.prototype.sayHi = function() {
    alert('hi');
};
Human.prototype.name = 'dan'; // will be shadowed if redefined on instances

var Coder = function() {};
Coder.prototype = Object.create(Human.prototype);
Coder.prototype.code = function() {
    alert('1010101');
};  
var jordan = new Coder();
console.log(jordan);

A polyfill for Object.create is available on MDN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top