javascript - 不同文件中的构造函数之间的部分继承(JavaScript)?

标签 javascript inheritance constructor

我在两个不同的 js 文件中有两个构造函数。我希望构造函数具有两种相同的方法(相同的名称和功能)和一种调用相同但工作方式不同的方法(名称相同但功能不同)。两个构造函数中还有一些相同的其他属性。

我尝试实现这一目标的方法是让一个构造函数继承另一个构造函数,然后声明一个与旧方法同名的新方法(见下文)。当构造函数位于同一个文件中时,这工作得很好(我相信),但是当它们位于单独的文件中时,我似乎失去了连接。继承不起作用。

代码看起来与此类似:

文件1:(有人建议删除第一行以避免循环,但似乎没有任何区别)

var Child = require("./Child");

var Parent = function(name, age) {
   this.name = name;
   this.age = age;
};

Parent.prototype.calculate1 = function(a, b) {
   return a + b;
};

Parent.prototype.calculate1 = function(a, b) {
   return a - b;
};

Parent.prototype.calculate3 = function() {
   return "Armageddon";
};

module.exports = Parent;

文件2:

var Parent = require("./Parent");

var Child = function(name, age) {
   Parent.call(this, name, age);
};

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

Child.prototype.calculate3 = function() {
   return "Deep Impact";
};

module.exports = Child;

所以,我想这更像是两个问题。 1)这是解决我的问题的好方法吗? 2)为什么当构造函数位于单独的文件中时它不起作用?在 Webstorm 中,我收到通知,方法调用(在 Parent.call 中)是未解析的函数或方法调用。

提前致谢!

最佳答案

您的示例存在一些问题。

  1. 两个文件之间存在循环依赖关系,因为它们都相互依赖。一般来说,这是一个坏主意。文件不应同时相互依赖,因为这会导致意外行为。
  2. 您需要使用第三个构造函数来解决您的问题,称为 Person 或其他东西。 ParentChild都应该继承自Person,并且你应该在Person中定义公共(public)方法,以及它们在各个文件上有所不同。

以下是它应该如何工作的示例:

// Person.js
function Person (name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.someShareMethod = function (a, b) {
  return a + b;
};

module.exports = Person;

// Parent.js
var Person = require('./Person');

function Parent (name, age) {
  Person.call(this, name, age);
}

Parent.prototype = Object.create(Person.protoype);

Parent.prototype.someSelfMethod = function (a, b) {
  return a * b;
};

module.exports = Parent;

// Child.js
var Person = require('./Person');

function Child (name, age) {
  Person.call(this, name, age);
}

Child.prototype = Object.create(Person.protoype);

Child.prototype.someSelfMethod = function (a, b) {
  return a - b;
};

module.exports = Child;

话虽如此,继承的一般概念应该有效。一旦构造函数可以从另一个构造函数继承,这是一个非常好的实践。我分解了你的代码(删除了循环引用),在本地运行它,并得到了预期的输出:

var Parent = require('./Parent'),
    Child = require('./Child');

var p = new Parent('Bob', 40);

console.log(p.calculate3());

var c = new Child('Stan', 12);

console.log(c.calculate3());

记录了这个:

Armageddon
Deep Impact

如果你没有明白这一点,我认为问题在于你如何使用你的类。

关于javascript - 不同文件中的构造函数之间的部分继承(JavaScript)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33601909/

相关文章:

java - 为什么 Java 中的每个对象都隐式扩展 java.lang.Object 类?

c++ - 在构造函数上 union 使用已删除函数的类

c# - 为什么 c# 编译器在使用具有 new() 约束的泛型类型调用 new 时发出 Activator.CreateInstance?

java - 第三方类扩展难

java - java中构造函数的问题

javascript - 如何使 AngularJS 指令在不隔离范围的情况下明确定义其依赖项

javascript - JStree 异步搜索

javascript - 滑动门按钮无法正确点击

javascript - jquery/javascript代码获取网页主页面的全文内容(包括链接文本,不包括图片)

python - Python中的继承,需要在子类中定义某些方法