Javascript对象方法范围 - 方法失败

时间:2016-03-09 11:23:04

标签: javascript oop object methods scope

对象方法失败,但属性记录正常。 所以我在全局范围内声明了一个变量,并尝试在函数中为它分配一个对象。属性“id”正确跟踪,但该方法会导致错误。我找了一个类似的帖子,但找不到任何东西。

我宁愿在Javascript中使用OO编程,所以如果你能给我一个指针来解决这个问题会很棒。提前谢谢。

var currentEnemyPieceObject; // this gets set in the play function

function EnemyPieceObject( _id ){

  this.id = _id;
  this.pathArray = [];
  this.active = false;

}

EnemyPieceObject.prototype = {

  constructor:EnemyPieceObject,
  addPointToPathArray:function( xPos, yPos ){ 
    var point = { "x":xPos, "y":yPos };
    this.pathArray.push( point );
  }
}


function play() {

  currentEnemyPieceObject  =  new EnemyPieceObject( 0 );

  console.log( currentEnemyPieceObject.id ); // result is 0

  currentEnemyPieceObject.addPointToPathArray( 0, 0 );
  // results in error
  // Uncaught TypeError: Uncaught TypeError:
  // currentEnemyPieceObject.addPointToPathArray is not a function

}

1 个答案:

答案 0 :(得分:1)

问题可能是您在初始化对象之前调用了play()函数。在控制台窗口打开的情况下运行下面的代码片段(通常为F12)。您报告的错误发生在太早调用play()时。但是,它会在以后调用时按预期工作。



var currentEnemyPieceObject; 

try {
  play();
}
catch(e) { console.error( e.message ); } 
// prints "currentEnemyPieceObject.addPointToPathArray is not a function"

function EnemyPieceObject( _id ){
  this.id = _id;
  this.pathArray = [];
  this.active = false;
}
EnemyPieceObject.prototype = {
  constructor:EnemyPieceObject,
  addPointToPathArray:function( xPos, yPos ){ 
    var point = { "x":xPos, "y":yPos };
    this.pathArray.push( point );
  }
}
function play() {
  currentEnemyPieceObject  =  new EnemyPieceObject( 0 );
  currentEnemyPieceObject.addPointToPathArray( 0, 0 );
}

play(); // no errors

console.info( typeof currentEnemyPieceObject.addPointToPathArray );  // prints "function"