Search code examples
javascriptprototypal-inheritance

How can I set a prototype function without using the new keyword


In a trivial example of prototype inheritance, I wanted to set the Person object as the parent class of Student object, but I don't want use the new keyword at the time of setting the prototype for the Student class as this would be wrong. But somehow this code doesn't work. Any help?

var Person = function(name) {
  var that = this;
  this.name = name;
  var _log = function() {
    console.log("Hello", that.name)
  };
  return {
    log: _log
  };
};

var Student = function(name) { 
  Person.call(this, name);  
  var _getCollegeName = function() {
    console.log("MIT")
  };
  return {
    getCollegeName: _getCollegeName
  };
};

Student.prototype = Object.create(Person);
//Student.prototype = new Person("Soham"); want to avoid this as the value should be passed from child class

var s = new Student("Soham");
s.log();
//s.getCollegeName();

Solution

  • You can set getCollegeName as a property of Person() call, return Person object

    var Person = function(name) {
      var that = this;
      this.name = name;
      var _log = function() {
        console.log("Hello", that.name)
      };
      return {
        log: _log
      };
    };
    
    var Student = function(name) {
      var p = Person.call(this, name);
    
      var _getCollegeName = function() {
        console.log("MIT")
      };
    
      p.getCollegeName = _getCollegeName;
    
      return p
    };
    
    Student.prototype = Object.create(Person);
    //Student.prototype = new Person("Soham"); want to avoid this as the value should be passed from child class
    
    var s = Student("Soham");
    s.log();
    s.getCollegeName();