[英]Method chaining in class in javascript
I am new in javascript. 我是javascript新手。 And I'm trying to figure out how classes work.
我正在尝试弄清楚类的工作方式。 I have this piece of code:
我有这段代码:
class TestObject {
constructor(initialNumber) {
this.result = initialNumber;
}
add(number) {
this.result += number;
return this;
}
}
const value = new TestObject(7)
.add(2)
.add(3);
console.log(value)
Value returns like this {result: 12}
But I need it to be just the integer 12
. 值返回像这样
{result: 12}
但是我需要它只是整数12
。 Is there any way to fix this by making changes only in the class body ?
是否可以通过仅在类主体中进行更改来解决此问题?
As your value
variable is an instance of TestObject
, so you can use 由于您的
value
变量是TestObject
的实例,因此您可以使用
console.log(value.result);
class TestObject { constructor(initialNumber) { this.result = initialNumber; } add(number) { this.result += number; return this; } } const value = new TestObject(7) .add(2) .add(3); console.log(value.result);
...by making changes only in the class body ?
... 仅通过在班级主体中进行更改?
No. You'd have to change something outside it as well, because your add
method returns an object, not a number. 不。您还必须在其外部进行更改,因为您的
add
方法返回的是对象,而不是数字。 So something has to say "I want a number instead please." 因此,必须说“我想要一个电话号码”。
If you add a valueOf
method to your class: 如果将
valueOf
方法添加到类中:
valueOf() {
return this.result;
}
...then the thing outside the class body could be just a +
: ...然后类主体之外的东西可能只是一个
+
:
console.log(+value);
...but that's still outside the class body. ...但是那仍然不在全班范围内。
Live example: 现场示例:
class TestObject { constructor(initialNumber) { this.result = initialNumber; } add(number) { this.result += number; return this; } valueOf() { return this.result; } } const value = new TestObject(7) .add(2) .add(3); console.log(+value);
This is happening because you returning the result from your method so the value will be a object {result:12} , If you want to see the execution and debug it, please add debugger;
发生这种情况是因为您从方法中返回了结果,所以该值将是一个对象{result:12} ,如果要查看执行并对其进行调试,请添加
debugger;
to any line you need you can understand what is getting; 对于您需要的任何线路,您都可以了解得到的结果;
class TestObject {
constructor(initialNumber) {
this.result = initialNumber;
}
add(number) {
this.result += number;
debugger;
return this;
}
}
const value = new TestObject(7)
.add(2)
.add(3);
debugger;
console.log(value)
with the code what you wrote, if you change the Console.log(value.result)
you will get the desired result . 使用您编写的代码,如果更改
Console.log(value.result)
,将获得所需的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.