【问题标题】:How do i call the constructor of a superclass with parameters in Javascript?如何在 Javascript 中使用参数调用超类的构造函数?
【发布时间】:2011-08-07 05:43:06
【问题描述】:

我有这个超类,它有两个私有元素和两个访问它们的方法:

function superclass(a,b) {
    var x = a;
    var y = b;
    this.getX = function() {return x;}
    this.getY = function() {return y;}
}

我想创建一个名为“ChildClass”的子类,它在其构造函数中调用超类构造函数,并为其提供两个参数。所以我可以说 parent = new SuperClass(2,3) 我还需要能够说 child = new ChildClass(3,4) 当我写类似 alert(child.getX()) 的东西时,浏览器会提示“ 3"。有谁知道怎么做?

【问题讨论】:

标签: javascript


【解决方案1】:

IIRC,要在 JavaScript 中创建构造函数层次结构,您需要自己编写。

这意味着,

function SuperClass {
}

function SubClass {
  this.inheritFrom = SuperClass;
  this.inheritFrom();
}

SubClass.prototype = new SuperClass();

或者,这仍然是首选技术:

function SuperClass {
}

function SubClass {
}

SubClass.prototype = new SuperClass();
SubClass.prototype.constructor = SubClass;

有一些库可以使 JavaScript 继承减少 PITA。

我建议您阅读 David Flannagan 的关于 JavaScript 的书,其中一部分是关于原型的。

【讨论】:

  • 问题是关于带参数的超类。您在回答中根本没有解决这个问题。
猜你喜欢
  • 2013-01-15
  • 1970-01-01
  • 2013-08-03
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 2021-09-19
  • 2015-12-18
相关资源
最近更新 更多