原型函数中“每”方法的问题

时间:2019-01-30 15:40:31

标签: javascript constructor prototype

我遇到了以下问题:函数中的every方法返回undefined,因此ableToMoveAll函数返回无论如何都会下降。请查看下面的代码,并为我提供帮助:

var SQUADS = [];

function MilitaryUnit(name, maxHealth, maxEnergy){
    this.squadName = name;
    this.squadMaxHealth = maxHealth;
    this.squadCurrentHealth = maxHealth;
    this.squadMaxEnergy = maxEnergy;
    this.squadCurrentEnergy = maxEnergy;

    this.travel = function(dist){
        if (dist > this.squadCurrentEnergy) {
            alert("You can't go this far");
        }
        this.squadCurrentEnergy -= dist;
    }
    this.ableToMove = function(dist){
        return this.squadCurrentEnergy >= dist;
    }
}

var squadOfHorses = new MilitaryUnit("Horses", 50, 100);
SQUADS.push(squadOfHorses);
var squadOfSoldiers = new MilitaryUnit("Soldiers", 40, 50);
SQUADS.push(squadOfSoldiers);
var squadOfMachines = new MilitaryUnit("Machines", 100, 50);
SQUADS.push(squadOfMachines);

Array.prototype.ableToMoveAll = function(dist){
    return this.every(function(el){
        el.ableToMove(dist)
    });
}

先谢谢您

1 个答案:

答案 0 :(得分:6)

不是every方法返回undefined,而是您传递给它的回调。您忘记了return语句:

return this.every(function(el){
    return el.ableToMove(dist)
//  ^^^^^^
});