简体   繁体   English

从子原型中调用父原型

[英]Call parent prototype from child prototype

My parent class is 我的父班是

   function Parent() {}

   Parent.prototype.get = function() {}

   Parent.prototype.start= function() {  this._start() }

My child is 我的孩子是

   function Child(){ Parent.call(this, arguments) }

   Child.prototype._start = function(){   this.get() /* error here - this.get is not a function*/ }  

   util.inherits(Child, Parent);

When I do 当我做

    new Child().start()

I got an error this.get is not a function . 我得到一个错误this.get is not a function How can I call parent prototype function? 如何调用父原型函数? Thanks. 谢谢。

As the use of util.inherits is discouraged, you should use extends for classes, but you seem to have just regular functions, which means you can set the prototype of the child to the same as the parent before starting to extend it further 由于不鼓励使用util.inherits ,你应该使用extends for classes,但你似乎只有常规函数,这意味着你可以在开始进一步扩展它之前将子模型设置为与父模型相同

 function Parent() {} Parent.prototype.get = function() { console.log('works fine'); } Parent.prototype.start = function() { this._start(); } function Child() { Parent.call(this, arguments); } Child.prototype = Parent.prototype; Child.prototype._start = function() { this.get(); } var instance = new Child(); instance.start(); 

Note that Parent and Child now have the same prototype, so by changing one, you'd be changing the other as well. 请注意,Parent和Child现在具有相同的原型,因此通过更改一个原型,您也可以更改另一个原型。
If for some reason you have to avoid that, using Object.create (or assign) would do that 如果由于某种原因你必须避免这种情况,使用Object.create (或assign)会这样做

Child.prototype = Object.create(Parent.prototype);

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

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