我只是想使用简单的代码来理解原型继承。
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
根据我的理解,它不应引发错误。我在做错什么吗?
答案 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);
}