javascript - 在函数中调用函数不起作用,未捕获的 TypeError
问题描述
这听起来可能与其他问题相似,但请听我说完。我有一个名为的函数bullet(x, y, w, h)
和一个名为this.trigger()
我想this.trigger()
在 keyDown 函数中调用的函数。
这是子弹功能
function bullet(x, y, w, h) {
//x value of bullet is the x value of the player + 27
this.x = player.x + 27;
//y value of bullet is the y value of the player
this.y = player.y;
//the width of the bullet
this.w = w;
//the height of the bullet
this.h = h;
//boolean for whether fired is true or false
this.fired = false;
//This function draws the player
this.draw = function() {
// states what x of the bullet is
this.x = player.x + 28;
//sets fillStyle to "red"
context.fillStyle = "red";
//Fills the rectangle red
context.fillRect(this.x,this.y,5,10);
};
//function which moves the bullet
this.trigger = function() {
//If this.fired = true; if statement runs
if(this.fired) {
//makes the bullet's y value go down by 10
this.y -= 10;
}
//If the bullet's y value is lower than 0; if statement runs
if (this.y < 0) {
//this.fired is now false
this.fired = false;
//sets the bullet y value to player y value
this.y = player.y;
}
};
}
这是按键功能:
// controls to shoot the bullet when the user presses the key
document.addEventListener("keydown", function(e) {
//if the player presses the spacebar run the statement
if(event.keyCode == 32) {
//bullet.fired is now equal to true
bullet.fired = true;
//calls bullet.trigger
bullet.trigger();
}
});
在这段代码中,它出现了错误:Uncaught TypeError: bullet.trigger is not a function at HTMLDocument。
这也是我第一次在 stackoverflow 上提出问题,因此感谢任何反馈。:)
解决方案
推荐阅读
- python - 是否可以支持将 X_PF、X_BM 作为参数的 AddJoint 的 Python 绑定?
- xml - XML 文件交换的合同测试
- c - munmap_chunk():无效的指针
- amazon-web-services - 当设备中有空间时,Docker 一直说“设备上没有剩余空间”
- c++ - C++ 避免舍入数字
- pine-script - 如果它违反特定价格,我如何使用 pine 脚本为 tradingview.com 上的第一根蜡烛重新着色?
- jquery - Bootstrap 导航栏切换器仅在第一次单击时起作用
- sql-server - 在 t-SQL 中创建一个函数,该函数将自动选择源表和目标表并更新特定列中的值
- maven - Eclipse RCP 集成测试:错误:找不到或加载主类
- c++ - c ++:从另一个派生类型创建派生对象