简体   繁体   English

Javascript中未定义函数的怪异错误

[英]A weird error of undefined function in Javascript

I defined a base and derived class, both defined a function called "getYear": 我定义了一个基类和派生类,都定义了一个名为“ 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());

The last statement will trigger a runtime error saying 最后一条语句将触发运行时错误,提示

 Cannot read property 'getYear' of undefined

Would you help to explain the reason? 您能解释一下原因吗? I think I have defined this function in both base/derived function. 我想我已经在基本/派生函数中定义了此函数。

The prototypes (instance methods) are declared on the Constructor , and only used on the instance . prototypes (实例方法)在Constructor上声明,并且仅在instance If you wanted to use the original prototype method based on the instance, you could do something like: 如果您想使用基于实例的原始原型方法,则可以执行以下操作:

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

where you get the getYear prototype from the original constructor . 从原始constructor获取getYear原型的位置。 However, this kind of defeats the purpose of using the prototypes in the instance sense. 但是,这种做法违反了在实例意义上使用原型的目的。

Here is your example, reworked to do what you were trying to: 这是您的示例,经过重新设计以执行您尝试做的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM