如何做一个不是函数的类方法?

问题描述 投票:0回答:1
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;
  };

有没有一种方法可以在类中返回值而不使用函数?

javascript class
1个回答
0
投票

是的,吸气剂:

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
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.