【问题标题】:TypeError: is not a function for the inheriting object functionTypeError:不是继承对象函数的函数
【发布时间】:2020-05-23 03:08:24
【问题描述】:

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

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

根据我的理解,它不应该抛出错误。我做错了吗?

【问题讨论】:

    标签: javascript inheritance prototypal-inheritance


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-19
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 2023-04-11
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      相关资源
      最近更新 更多