代码之家  ›  专栏  ›  技术社区  ›  left click

是否可以将对象评估为布尔值?

  •  1
  • left click  · 技术社区  · 6 年前
    class Test {
        is_valid = true;
    
        constructor (value) {
            this.value = value
        }
    
        is_less_than (number) {
            if (this.value >= number)
                this.is_valid = false;
            return this;
        }
    
        is_greater_than (number) {
            if (this.value <= number)
                this.is_valid = false;
            return this;
        }
    }
    
    const is_valid = new Test(5).is_less_than(10),
          is_valid2 = new Test(5).is_less_than(10).is_greater_than(7);
    
    if (is_valid)
        console.log(1); // 1
    else
        console.log(0);
    
    if (is_valid2)
        console.log(1);
    else
        console.log(0); // 0
    

    我想使用任何解决方案实现这个模式。我用valueof()、toString()、setting context、boolean等尝试过各种测试…我不确定是否可能。如果你知道的话,请告诉我。


    我没用的原因 有效的 属性是为了避免只使用方法结果不使用的对象的错误 有效的 .

    下面的模式也是可能的,但并不令人满意。

    new Test().is_less_than(10).is_valid(5)
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   FZs kangax    6 年前

    在您的代码中, is_valid is_valid2 是类的实例 Test ,所以它们是对象。
    检查 Test.is_valid 值,您应该使用如下内容:

    const is_valid = new Test(5).is_less_than(10).is_valid, 
          is_valid2 = new Test(5).is_less_than(10).is_greater_than(7).is_valid;