在函数内调用函数不起作用,未捕获TypeError

时间:2018-11-04 05:55:40

标签: javascript typeerror

这听起来可能与其他问题类似,但请听我说。我有一个名为bullet(x, y, w, h)的函数,还有一个名为this.trigger()的函数,我想在keyDown函数中调用this.trigger()

这是项目符号功能

	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();


	}

	});

在此代码中,出现了以下错误:未捕获的TypeError:bullet.trigger不是函数     在HTMLDocument中。

这也是我第一次问有关stackoverflow的问题,因此希望得到任何反馈。 :)

0 个答案:

没有答案
相关问题