class Library {
constructor(a){
this.total = a;
}
add(...a){
for (const arg of a) {
this.total += arg;
}
return this;
}
subtract(...b){
for (const args of b) {
this.total -= b;
}
return this;
}
result() {
console.log(this.total);
return this.total
}
}
$ = new Library(10); // inititliaize the base as 10
// var x = $.add(3,5).add(5,10).subtract(10).result;
// x should be 10+3+5+5+10-10 or basically 23
// var y = $.add(3,5).add(5,10).subtract(10,3,5).result to return 15
问题需要精确的线路。
var x = $.add(3,5).add(5,10).subtract(10).result;
问题需要链接一个方法“结果”,该方法“结果”不是我尝试过的函数
result = function(){
return this.total;
};
有没有一种方法可以在类中返回值而不使用函数?
是的,吸气剂:
class Library {
constructor(a){
this.total = a;
}
add(...a){
for (const arg of a) {
this.total += arg;
}
return this;
}
subtract(...b){
for (const args of b) {
this.total -= b;
}
return this;
}
get result() {
console.log(this.total);
return this.total
}
}