Javascript 未定义函数的奇怪错误

A weird error of undefined function in Javascript

我定义了一个 base 和 derived class,两者都定义了一个名为 "getYear":

的函数
function Base() {}
Base.prototype.getYear = function() {
    return 2015;
}

function Derived() {
    year = 2016;
}
Derived.prototype = new Base();
Derived.prototype.getYear = function() {
    return 2017;
}

var ins = new Derived();
console.log(ins.getYear());
console.log(ins.prototype.getYear());

最后一条语句会触发运行时错误

 Cannot read property 'getYear' of undefined

能帮忙解释一下原因吗? 我想我已经在 base/derived 函数中定义了这个函数。

prototypes(实例方法)在 Constructor 上声明,仅在 instance 上使用。如果你想使用基于实例的原始原型方法,你可以这样做:

var ins = new Derived();
ins.constructor.prototype.getYear();

从原始 constructor 获得 getYear 原型的地方。然而,这种做法违背了在实例意义上使用原型的目的。

这是您的示例,经过重新设计以实现您的目标:

function Base() {}
Base.prototype.getYear = function() {
  return 2015;
}

function Derived() {
  year = 2016;
}
Derived.prototype = new Base();
Derived.prototype.getYear = function() {
  return 2017;
}

var ins = new Derived();
console.log(ins.getYear());
console.log(ins.constructor.prototype.getYear());