【发布时间】:2020-02-26 01:04:41
【问题描述】:
我正在尝试在 JS 中开发一个供个人使用的游戏引擎。我想让我的引擎能够使用不同类的元素。我试图解决的一个这样的问题是将方法从一个类(比如一个链接函数的数学类)链接到我的主函数。
这是我希望它看起来像的示例:
let game = new Engine()
game.operator(5).sum(3).divide(2)
这可能是我的代码中的内容,尽管我不确定该怎么做。
class Engine {
constructor() {
//Set up engine here
/* This is where I am unsure how to link the following operator class to this one.
* Do I put it here in constructor or ...
*/
}
/* ... do I put it here? (Or not in this class at all?)
*
* This is what I tried doing as a function
*
* operator(input) {
* let op = new Operator(input);
* }
*/
}
class Operator {
/*The following class is different than the one I am using, but follows similar syntax:
* Basic usage: operator(5).sum(3, 4) => Should output 12
* How the class works is mostly irrelevant, just know it chains methods.
*/
constructor(input) {
this.input = input;
this.answer = this.input;
}
sum() {
let a = arguments[0]
for(var i = 1; i < arguments.length; i++) {
a += arguments[i];
}
this.answer += a;
return this;
}
divide() {
let a = arguments[0];
for(var i = 1; i < arguments.length; i++) {
a *= arguments[i];
}
this.answer /= a;
return this;
}
}
如何让一个类能够链接不同类的方法?
【问题讨论】:
-
Engine中的operator函数可以返回您在那里构建的 Operator 对象。很高兴您可以在单个语句中链接事物,但不要过度。
标签: javascript function class