简体   繁体   English

从父类访问子类原型

[英]Accessing child class prototype from parent class

I am trying to implement a base class method, that have the same logic for all child classes, but would use some of their variables, that are specific to them. 我正在尝试实现一个基类方法,该方法对所有子类都具有相同的逻辑,但是会使用它们特定于它们的一些变量。

function A() {}
A.prototype.foo = 'bar';
A.prototype.getFoo = function () {
    console.log('Called class: ' + this.constructor.name);
    return this.foo;
};

function B() {}
B.prototype.foo = 'qaz';
require('util').inherits(B, A);

console.log(B.prototype.getFoo());

The last line prints bar , but getFoo() also prints Called class: B . 最后一行打印bar ,但是getFoo()也打印Called class: B So I'm wondering, since I can access the child's constructor, is there a way to access child's prototype through it? 所以我想知道,既然我可以访问子级的构造函数,是否有办法通过它访问子级的原型?

require('util').inherits resets B.prototype to a new object that inherits A . require('util').inherits B.prototype重置为继承A的新对象。
Any properties you set on the old prototype are lost. 您在旧原型上设置的所有属性都将丢失。

If you set B.prototype.foo after calling inherits() , it will work fine. 如果调用B.prototype.foo inherits() 之后设置B.prototype.foo ,它将正常工作。

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

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