gpt4 book ai didi

javascript - 如何将链函数从一个类添加到另一个类?

转载 作者:行者123 更新时间:2023-11-30 09:11:27 25 4
gpt4 key购买 nike

我正在尝试用 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;
}

}

我怎样才能让一个类能够链接来自不同类的方法?

最佳答案

链接模式是让实例保持链状态,并提供返回链状态的“值”方法。要在两个类之间进行链接,我想我会包含一个返回另一个类实例的特殊值方法。 (为了让读者保持导向,将其命名为指示类型更改的名称)...

class ObjectA {
constructor(string) {
this.chainValue = string
this.string = string
}

transformA() {
this.chainValue = this.chainValue.toUpperCase()
return this
}

transformB() {
this.chainValue = this.chainValue + "bar"
return this
}

// the regular value method
get value() {
return this.chainValue
}

// like the value method, but named to explicitly return MyNumber
get numberValue() {
return new MyNumber(this.value.length)
}
}

class MyNumber {
constructor(int) {
this.chainValue = int
this.int = int
}

add(n) {
this.chainValue += n
return this
}

get value() {
return this.chainValue
}
}

let a = new ObjectA("foo")
console.log(
a
.transformB() // append "bar"
.transformA() // convert to upper case
.numberValue // return a number (arbitrarily, the length of the chain state)
.add(12) // add 12
.value // expect 18
)

关于javascript - 如何将链函数从一个类添加到另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58630328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com