【问题标题】:over-ride a method in extended class in node js and access variable覆盖节点js中扩展类中的方法并访问变量
【发布时间】:2018-07-11 03:22:08
【问题描述】:

如何在子原型中访问父原型变量“id”。

const util = require('util');

const Parent = function () {};

Parent.prototype.access = function() {
    var id = 1;
};

const Child = function () {};

util.inherits(Child, Parent);

child.prototype.access = function() {
    //access Parent.prototype.access variable 'id' here
}

有什么想法吗??

【问题讨论】:

  • 你不能。 id 只存在于父函数的范围内。在实例上设置它。

标签: javascript node.js oop prototypal-inheritance


【解决方案1】:

您可以使用 JS 类来做到这一点。

class Parent {
  constructor(id) {
    this.id = id;
  }

  access() {
    this.id = 1;
    console.log('Parent access');
  }
}

class Child extends Parent {
  access() {
    console.log(`Child access: ${this.id}`);
  }
}

const d = new Child(5);
d.access(); // Child access: 5

【讨论】:

  • 感谢您的回答。我只需要使用原型继承来实现,不能使用 JS 类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 2012-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
相关资源
最近更新 更多