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

Javascript Object method scope - method fails

本文关键字:方法 失败 范围 Javascript 对象      更新时间:2023-09-26

对象的方法失败,但属性日志正常。所以我在全局范围内声明了一个变量,并尝试在函数中为其分配一个对象。属性"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
}

问题可能是您在初始化对象之前调用 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"