【问题标题】:Constructors Which Create Constructors (JavaScript)创建构造函数的构造函数 (JavaScript)
【发布时间】:2016-02-18 00:54:30
【问题描述】:

在我正在制作的模拟中,我将有一个 Element 类,我将使用有关该元素属性(熔化和沸腾温度、与其他元素的反应规则、颜色、密度等)的参数调用它.) 创建元素的基本类型(水、氧、碳等)。从这些中,我只是想从我将拥有的水、氧气和碳模板中创建新的“原子”。我想知道是否有办法使用构造函数(元素)来创建一个新的构造函数(比如水)?例如,我希望能够做这样的事情。

var Element = function(/* params */) {
    // common element properties and basic functions
}
var Water = new Element(); // create the new element
var WaterAtom = new Water(); // create the atom (an instance of the element)
// draw the atom, manipulate it, react with other atoms, etc.

我基本上是在问,一个构造函数可以创建另一个构造函数吗?我希望这样,这样我就不必创建大量扩展基本 Element 类的 .prototype 代码。

【问题讨论】:

  • 这应该完成什么?您在哪里为 Water 类指定新行为?
  • 不,一个 constructor 不能创建另一个构造函数,你应该认为它是一个简单的构造函数生成 function,它不会被调用new.
  • 这些东西应该是Element 的子类吗?那么Element 是构造元素实例的构造函数——而不是构造函数。
  • 顺便说一句,我想你的意思是 Hydrogen 不是 Water
  • 这里不是简单的问JavaScript继承吗?

标签: javascript object constructor


【解决方案1】:

你可以写一个实用函数来生成Element的子类:

function Element() {}

function subElement() {
  function SubElement() {}
  SubElement.prototype = Object.create(Element.prototype);
  return SubElement;
}

var Water = subElement();
var waterAtom = new Water();

【讨论】:

  • Object.create(Element); - 不。
  • @SimpleJ 嗯...我试试看。
  • @Bergi Woops。我想我已经太习惯类语法了
【解决方案2】:

我认为你正在寻找的是

function Element(…) {
    // init properties that all elements share
}
Element.prototype.… = function(…) { … }; // add all methods of elements

Element.makeType = function(rules) {
    function ElementType(…) {
        Element.call(this, …);
    }
    ElementType.prototype = Object.create(Element.prototype);
    ElementType.prototype.constructor = ElementType;
    ElementType.prototype.rules = rules;
    return ElementType;
};

这样你就可以像使用它

var Water = Element.makeType(function(…) {
    // do whatever makes water special
});

var drop = new Water(…);

【讨论】:

  • 不错!我试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 2011-05-13
  • 2013-04-29
  • 2012-06-30
  • 1970-01-01
相关资源
最近更新 更多