如何在类中运行函数。使用Javascript

时间:2016-04-11 05:43:43

标签: javascript function this

我很难在类中调用函数。当我开始研究这个时,我已经开始运行,但在进行修改之后,我无法使其正常工作:(( 您可以忽略我的警报,因为我只是将它们放在那里检查函数是否被调用 我有功能" Unit"这对我来说是一堂课。然后我在下面叫它。
从下面的代码中,new Unit(args)未完成。它停在this.direction=this.setDirection(); 并且由于某种原因没有调用this.setDirection()。任何人都可以看看,告诉我出了什么问题?
谢谢!

var teamBlack = [];

var bking = new Unit("black", "king", new Coords(3,1, false));
teamBlack.push(bking);

function Unit(team, type, coords) {

    alert("Unit started " + count);
    this.team = team;
    this.type = type;

    this.position = coords;
    this.highlight = false;
    alert("before setdirection");
    this.direction = this.setDirection();
    alert("this " + this.type);

    this.setDirection = function () {
        alert("setDirection Started ");
        alert(this.type);
        var tempDir = [];
        switch (this.type) {
            case "king" :
                alert("this is king");
                tempDir = [this.N(), this.NW(), this.W(), this.SW(), this.S(), this.SE(), this.E(), this.NE()];
                break;
            case "bishop" :
                tempDir = [this.NW(), this.SW(), this.SE(), this.NE()];
                break;
            case "rook" :
                tempDir = [this.N(), this.S(), this.W(), this.E()];
                break;
            case "pawn" :
            {
                if (this.team == "white") {
                    tempDir = [this.S()];
                } else {
                    tempDir = [this.N()];
                }
                break;
            }
            case "queen" :
            {
                if (this.team == "white") {
                    tempDir = [this.N(), this.W(), this.SW(), this.S(), this.SE(), this.E()];
                } else {
                    tempDir = [this.N(), this.NW(), this.W(), this.S(), this.E(), this.NE()];
                }
                break;
            }

        }
        tempDir = tempDir.filter(function (dir) {
            return dir.x > -1 && dir.x < 3 && dir.y > -1 && dir.y < 4 && dir.c == false;
        });

        return tempDir;
    }
}

1 个答案:

答案 0 :(得分:0)

确保定义变量,然后在调用this.setDirecton = function()...之前放置this.setDirection()

请参阅JSFiddle