Javascript 对象方法范围 - 方法失败
Javascript Object method scope - method fails
对象的方法失败,但属性日志正常。所以我在全局范围内声明了一个变量,并尝试在函数中为其分配一个对象。属性"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"
相关文章:
- Jasmine单元测试在监视服务方法时失败
- select方法在Firefox和Chrome中失败
- 插入失败:流星 1.3 中的方法并做出反应
- Javascript:在对象实例方法上使用apply()方法失败
- $http-get方法即使使用AngularJS中.Net WebApi的有效json也会失败
- *简单*解析云代码查询失败”;TypeError:无法调用方法'获取'未定义的“检索该信息”;
- jqxGrid失败并出现错误“;Object[Object Object]没有方法'jqGrid'&”;
- PageMethods调用使用1参数成功,但在2上失败(未知web方法)
- Javascript方法定义失败
- Javascript 对象方法范围 - 方法失败
- JavaScript Windows.open() 方法失败
- 使用 jQuery 1.4.4 由于某种原因,这个简单的方法失败了
- Canvas:drawImage方法失败,没有错误
- SoundCloud Javascript SDK 3.0 put方法失败
- 动态样式更改方法失败
- jQuery $. getjson()方法失败时,响应是text/html
- Redis客户端和节点js - hgetall方法失败,结果为空
- js方法失败(抛出异常?),firebug不报告
- jquery .ajax() 方法失败
- Jquery .click方法失败