【发布时间】:2020-02-08 13:00:43
【问题描述】:
这可能是一个愚蠢的问题,但是否可以在类的方法调用上创建一个新的 this? 例如:
const foo = new Foo();
console.log(foo.a(1).b(2));
// for example, outputs 3 (1+2)
// the a method will create a new namespace and attach 1 to it, and b will use that new namespace
console.log(foo.b(2));
// this will result in an error, as there is no new namespace from the a method anymore, so b cannot add to anything?
也许这太难理解了,抱歉。
class Foo {
a(number) {
this.a = number;
return this;
}
b(number) {
return this.a + number;
}
}
这将是它使用相同 this 变量的代码 - 这不符合我想要的但是我目前拥有的。
// pseudo
class Foo {
a(number) {
const uniqueVariable = number
return uniqueVariable
// it'll somehow pass the number from this method to the next method
}
// where it can be used with the second method's input
b(uniqueVariable, number) {
return uniqueVariable + number
}
}
foo.a(1).b(2) = 3
这个例子显然会导致错误,因为 a() 的返回值是一个数字,而不是再次使用方法的东西。 如果我需要进一步解释,请告诉我——我很难正确解释。
【问题讨论】:
-
只有
class Foo { ... },不是class Foo() { ... }。从class Foo()中删除您的()
标签: node.js oop method-chaining