2016-04-11 3 views
0

Мне сложно называть функцию внутри класса. Когда я начал работать над этим, я начал работать, но после внесения изменений я не могу заставить его работать: ((
Вы можете игнорировать мои оповещения, потому что я просто помещал их туда, чтобы проверить, вызвана ли функция или нет .
у меня есть функция «Unit», который является классом для меня. затем я называю его ниже.
снизу кода, который new Unit(args) не получает завершен. Он останавливается на this.direction=this.setDirection(); и this.setDirection() не называется по какой-то причине. Можно ли посмотреть и сказать мне, что пошло не так?
Спасибо!Как запустить функцию внутри класса. Javascript


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

Вы звоните * this.setDirection * перед тем, как присвоили ей значение. Вы не можете этого сделать. Переместите его на потом. Возможно, вы слышали о том, что объявления функций «подняты», но ваше назначение в * setDirection * не является объявлением, это простое назначение функции для свойства объекта. – RobG

ответ

2

Этот код является неправильным, потому что вы пытаетесь вызвать функцию вызова, которая еще не существует в вашем классе. Я рекомендую вам переместить эту функцию в прототипе. Например:

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

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

Убедитесь, что переменные определены, а затем положить this.setDirecton = function()... перед вызовом this.setDirection().

См. JSFiddle.

0

Я хотел бы улучшить свой код, разделяя обязанности:

//create the class Unit 

    function Unit(team, type, coords) { 

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

     this.position = coords; 
     this.highlight = false; 
    } 

Затем указать новый метод для вашего класса:

Unit.prototype.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; 
     }); 
     alert("before setdirection"); 
     this.direction = tempDir;//setMethod doesn't return thing but set something somewhere 
     alert("this " + this.type); 
    }; 

и теперь вы вызываете свой экземпляр класса:

var teamBlack = []; 

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

Предлагаю вам посмотреть на this link

+0

после ваших строк .. sorr Я забыл набрать его .. исправление –

0

Вам необходимо использовать функцию setDirection в качестве прототипа вашего класса Unit.

Unit.prototype.setDirection = function() { 
    //setDirection functionality 
} 

В прототипе у вас есть доступ к вашим свойствам класса через this.

Проверить это jsFiddle: https://jsfiddle.net/urtr3quc/

Смежные вопросы