![](/img/trans.png)
[英]Call schema method without create a new Model object with Nodejs/Mongoose
[英]Create new this on method call
這可能是一個愚蠢的問題,但是是否可以在類的方法調用上創建一個新的 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() 的返回值是一個數字,而不是再次使用方法的東西。 如果我需要進一步解釋,請告訴我 - 我很難正確解釋它。
在我的解決方案中,我決定創建兩個變量來保存每個方法的值。 ( https://jsbin.com/wozuyefebu/edit?js,console )
如果isSingle
參數設置為true
則a()
方法將返回一個數字。 如果沒有,它將返回this
對象,允許您鏈接b()
方法。 這可能是一個黑客,但我相信它可以解決您的問題。
我在我的博客上寫了關於 Javascript 和 Web 開發的內容 :) https://changani.me/blog
class Foo {
constructor() {
this.aValue = 0;
this.bValue = 0;
}
/**
* @param {Number} value
* @param {Boolean} isSingle
* @returns {Object/Number}
*/
a(value = 0, isSingle = false) {
this.aValue = value;
return isSingle ? this.aValue : this;
}
/**
* @param {Number} value
* @returns {Number}
*/
b(value = 0) {
this.bValue = this.aValue + value;
return this.bValue;
}
}
const x = new Foo();
console.log("Should return 3: ", x.a(2).b(1));
console.log("Should return an 2: ", x.a(2, true));
console.log("Should return an instance of the object: ", x.a(2));
console.log("Should return 1: ", x.b(1));
console.log("Should return 0: ", x.a().b());
如果您希望能夠在方法的返回值上調用方法,那么您應該從這些方法中返回this
。 但是,您將需要一個額外的方法,比如value()
來實際獲得 sum 的結果。
一種可能的方法如下所示。
class Foo { _a = 0; _b = 0; a(number) { this._a = number; return this; } b(number) { this._b = number; return this; } value() { return this._a + this._b; } } const foo = new Foo(); console.log(foo.a(1).b(2).value()); console.log(foo.b(5).value());
如果意圖是foo.a(1).b(2)
改變foo
,或者如果你不介意改變foo
,這里的其他答案有效。
但是如果你只希望foo.a(1).b(2)
返回3
而不修改foo
,那么你需要返回一個新的Foo
。
現在,如果你真的一心想console.log()
打印3
而不是像Foo { value: 3 }
這樣的東西,你還可以自定義inspect()
(假設問題是用node.js
標記的)。
全部一起:
const util = require('util');
class Foo {
constructor(value) {
this.value = value || 0;
}
add(value) {
return new Foo(this.value + value);
}
a(value) {
return this.add(value);
}
b(value) {
return this.add(value);
}
[util.inspect.custom]() {
return this.value;
}
}
const foo = new Foo();
console.log(foo);
console.log(foo.a(2).b(1));
console.log(foo);
輸出:
0
3
0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.