Search code examples
javascriptinheritanceprototypal-inheritance

TypeError: is not a function for the inheriting object function


I am just trying to understand prototypical inheritance using simple code.

function Place() {

}

Place.prototype.airportCode = function(code) {
    console.log('Airport code is: ' + code);
}

function City(cityName) {
    this.name = cityName;
}

City.prototype.railwayStateCode = function(code) {
    console.log('Railway station code is: ' + code);
}

City.prototype = Object.create(Place.prototype);

const sydney = new City('Sydney');

const melbourne = new Place();

When I try to

sydney.railwayStateCode('SYD');

I get an error

TypeError: sydney.railwayStateCode is not a function

As per my understanding, it should not throw an error. Am I doing something wrong?


Solution

  • You overriding the prototype here:

    City.prototype = Object.create(Place.prototype);
    

    To make it work change the order like this:

    City.prototype = Object.create(Place.prototype);
    
    City.prototype.railwayStateCode = function(code) {
        console.log('Railway station code is: ' + code);
    }