javascript - 如何在类中运行函数。 JavaScript

标签 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;
    }
}

最佳答案

此代码是错误的,因为您尝试调用类中尚不存在的函数。我建议你在原型(prototype)中移动这个功能。例如:

function Unit() {
    //this is your constructor
}

Unit.prototype.setDirection = function() {
    //your code of setDirection function
}

关于javascript - 如何在类中运行函数。 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36540634/

相关文章:

Javascript 不替换字符串

javascript - 使用javascript将图像文件转换为base64字符串

c - 返回一个 float 变量会失去其在 C 中的精度

c++ - 你怎么知道当前对象是什么?

javascript - 如何将 requestAnimationFrame 与 TypeScript 对象一起使用?

javascript - 警报框不打印变量值

javascript - 如何将内部 setState 函数重构为静态类方法?

C++ 函数指针作为参数

php - JavaScript 在函数之间传递变量并处理它们

javascript - 在JavaScript中使用 'prototype'和 'this'?