为什么我班上的“口渴”方法不起作用?

时间:2019-02-03 03:05:29

标签: javascript

我不知道为什么方法渴不返回true。没什么多说的,但是对于我来说,函数本身似乎还不错,但是会引发类型错误。

listed_list.dirs("Users/ronakshah/Downloads/")

#$Users
#$Users$ronakshah
#$Users$ronakshah$Downloads
#[1] "Users/ronakshah/Downloads/"

该测试未通过:

  class Vampire {
        constructor(name, pet) {
            this.name = name;
            if (pet === undefined) {
                this.pet = 'bat';
            } else {
                this.pet = pet;
            }
        }
        thirsty() {
            return true
        };
    }

3 个答案:

答案 0 :(得分:1)

您不能像这样调用Vampire.thirsty,因为thirsty不是 static 方法。您要么需要创建class的新实例,要么将thirsty方法声明为 static

静态方式:

class Vampire {
  constructor(name, pet) {
    this.name = name;
    if (pet === undefined) {
      this.pet = 'bat';
    } else {
      this.pet = pet;
    }
  }
  static thirsty() { // declare as static
    return true
  };
}

console.log(Vampire.thirsty());

新实例(使用方括号调用方法本身:thirsty()):

class Vampire {
  constructor(name, pet) {
    this.name = name;
    if (pet === undefined) {
      this.pet = 'bat';
    } else {
      this.pet = pet;
    }
  }
  thirsty() { // declare as static
    return true
  };
}

let vlad = new Vampire("Vlad", "dog"); // create an instance of the class Vampire (an object)
console.log(vlad.thirsty()); // call the thirsy method on the object (ensure you use the round brackets ())

答案 1 :(得分:1)

它的正常工作,只要你创建类的新实例:

class Vampire {
    constructor(name, pet) {
        this.name = name;
        if (pet === undefined) {
            this.pet = 'bat';
        } else {
            this.pet = pet;
        }
    }
    thirsty() {
        return true
    };
}

var pet = new Vampire('boo');

console.log(pet.thirsty());

也许您正试图像Vampire.thirsty()那样访问它?如果是这样的话,你应该让一个static method

class Vampire {
    constructor(name, pet) {
        this.name = name;
        if (pet === undefined) {
            this.pet = 'bat';
        } else {
            this.pet = pet;
        }
    }
    static thirsty() {
        return true
    };
}

console.log(Vampire.thirsty());

编辑:测试的问题在于您正在测试thirsty,而不是thirsty()thirsty是一个函数,调用该函数将返回true。简单地更新测试,实际调用thirsty

it('should have vampire return true if thirsty', function() {
  var vampire = new Vampire('Andy');
  assert.equal(vampire.thirsty(), true);
});

答案 2 :(得分:0)

在测试中,您错误地比较了函数thirstytrue

assert.equal(vampire.thirsty, true);

您不是在调用thirsty并检查返回值。

您需要这样调用方法:

assert.equal(vampire.thirsty(), true);