【问题标题】:Javascript Object method scope - method failsJavascript 对象方法范围 - 方法失败
【发布时间】:2016-06-23 17:54:18
【问题描述】:

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

}

【问题讨论】:

  • 错误消息中的 "this.currentEnemyPieceObject..." 与您在此处显示的实际代码不匹配...!?
  • 感谢 deceze - 是的 - 我只是在尝试其他一些选项。谢谢 - 它仍然失败。我已经粘贴了正确的错误。 (鹰眼:))
  • 嗯...该代码不会引发任何此类错误...
  • 这段代码可以正常工作...有什么问题?您使用的是什么浏览器(和版本)?我实际上是复制粘贴...没有修改任何单个字符 - 没关系。

标签: javascript oop object methods scope


【解决方案1】:

问题可能是您在初始化对象之前调用了 play() 函数。在控制台窗口打开(通常是 F12)的情况下运行下面的代码 sn-p。您报告的错误发生在 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"

【讨论】:

  • Roberto,谢谢,我学到了一些东西,得到了很好的回答 - 感谢您抽出宝贵的时间 :) 所以这个故事的寓意是在用 Javascript 执行任何代码之前逐字定义您的所有类。 (我的 AS3 背景并没有让我得出这个结论)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多