[英]Parent method is not recognized by child - JavaScript Prototype Inheritance
--- apparently I did a mistake and the following code DOES work... --- ---显然我做错了,下面的代码确实起作用了...-
I am new to JavaScript and prototype inheritance. 我是JavaScript和原型继承的新手。 I come from a class-based inheritance language background. 我来自基于类的继承语言背景。
I'm trying to create a parent object that does some stuff in it's prototype's methods. 我正在尝试创建一个父对象,该对象在原型方法中做了一些工作。 It has a certain method (doSomething) that inside it calls another method (doNestedSomething). 它有一个确定的方法(doSomething),它在内部调用了另一个方法(doNestedSomething)。
function Parent (num)
{
this.num = num;
}
Parent.prototype.doSomething = function()
{
this.doNestedSomething();
};
Parent.prototype.doNestedSomething = function()
{
this.num++;
console.log(this.num);
};
Then I want to create a child that inherits from the super, and overrides the certain method. 然后,我想创建一个从超级继承的子对象,并重写特定方法。
function Child (num, st)
{
this.st = st;
Parent.call(this, num);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.doSomething = function()
{
this.st += " " + this.st;
console.log(this.st);
Parent.prototype.doSomething.call(this);
};
The problem is, that once it calls the super's doSomething method, inside it the doNestedSomething method somehow does not exist. 问题是,一旦它调用了上级的doSomething方法,在其内部就根本不存在doNestedSomething方法。
var child = new Child(0, "kawaii");
child.doSomething(); //Uncaught TypeError: this.doNestedSomething is not a function
I think I'm doing something wrong. 我想我做错了。 I looked around here about inheritance and prototype and tried to implement it as depicted there. 我在这里四处浏览有关继承和原型的信息,并尝试实现那里描述的那样。
But I can not find any information on how a child can call a super method, when the super method calls some other super method... 但是当超级方法调用其他超级方法时,我找不到有关孩子如何调用超级方法的任何信息...
I looked at John Resig's way to implement inheritance, but still do not see there an example for a child indirectly calling a parent method that does not exist... 我看了约翰·雷西格(John Resig)实现继承的方法 ,但仍然看不到有一个孩子间接调用不存在的父方法的示例。
I've just tested your exemple and it works well, 我刚刚测试了您的示例,效果很好,
For : 对于:
var child = new Child(0, "kawaii");
child.doSomething();
child.doSomething();
child.doSomething();
It output without exception : 输出无异常:
kawaii kawaii
1
kawaii kawaii kawaii kawaii
2
kawaii kawaii kawaii kawaii kawaii kawaii kawaii kawaii
3
Fiddle : https://jsfiddle.net/uwb7omx3/ 小提琴: https : //jsfiddle.net/uwb7omx3/
Tested on chrome 42 经过镀铬测试42
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.