TypeError:不是继承对象函数的函数

时间:2020-05-23 03:08:24

标签: javascript inheritance prototypal-inheritance

我只是想使用简单的代码来理解原型继承。

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();

当我尝试

sydney.railwayStateCode('SYD');

我遇到错误

TypeError: sydney.railwayStateCode is not a function

根据我的理解,它不应引发错误。我在做错什么吗?

1 个答案:

答案 0 :(得分:1)

您在此处覆盖了原型:

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

要使其正常工作,请更改顺序,如下所示:

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

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