Это может быть глупый вопрос, но возможно ли создать новое 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;
}
}
Это будет код, в котором используется та же самая переменная - это не соответствует тому, что я хотел, но это то, что у меня сейчас есть.
// 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
Этот пример, очевидно, вызовет ошибку, потому что возвращаемое значение () число, а не что-то, чтобы использовать метод снова. Пожалуйста, дайте мне знать, если мне нужно объяснить дальше - у меня возникли трудности с объяснением этого должным образом.