首页 > 解决方案 > 在函数中调用函数不起作用,未捕获的 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 上提出问题,因此感谢任何反馈。:)

标签: javascripttypeerror

解决方案


推荐阅读