0

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?

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.