Search code examples
javascriptprototypeundefinedradixderived

A weird error of undefined function in Javascript


I defined a base and derived class, both defined a function called "getYear":

function Base() {}
Base.prototype.getYear = function() {
    return 2015;
}

function Derived() {
    year = 2016;
}
Derived.prototype = new Base();
Derived.prototype.getYear = function() {
    return 2017;
}

var ins = new Derived();
console.log(ins.getYear());
console.log(ins.prototype.getYear());

The last statement will trigger a runtime error saying

 Cannot read property 'getYear' of undefined

Would you help to explain the reason? I think I have defined this function in both base/derived function.


Solution

  • The prototypes (instance methods) are declared on the Constructor, and only used on the instance. If you wanted to use the original prototype method based on the instance, you could do something like:

    var ins = new Derived();
    ins.constructor.prototype.getYear();
    

    where you get the getYear prototype from the original constructor. However, this kind of defeats the purpose of using the prototypes in the instance sense.

    Here is your example, reworked to do what you were trying to:

    function Base() {}
    Base.prototype.getYear = function() {
      return 2015;
    }
    
    function Derived() {
      year = 2016;
    }
    Derived.prototype = new Base();
    Derived.prototype.getYear = function() {
      return 2017;
    }
    
    var ins = new Derived();
    console.log(ins.getYear());
    console.log(ins.constructor.prototype.getYear());