我正在尝试使用 javascript 创建一个小游戏,一切都很顺利,直到我必须发射一些东西,我需要实例化一个“子弹”并发射它,但是当调用“newBullet()”时,我得到了一个“未捕获的类型错误:未定义不是函数”。 如何在另一个对象方法中实例化一个对象?
这就是我所做的
function bullet(){
//here it would be state for the bullet, like x and y and thigs
console.log("bullet created");
}
function gun(){
//state for the gun, amount of bullets and sort
console.log("gun created");
this.fire = function(){
//here we instantiate a bullet and fire it
console.log("begin fire");
var bullet = new bullet();
console.log("created bullet to fire");
}
}
var gun = new gun();
gun.fire();
最佳答案
在 javascript 中,你的变量会被提升。为了清楚这意味着什么,编译器将您编写的代码视为您编写的代码:
function gun(){
//state for the gun, amount of bullets and sort
console.log("gun created");
this.fire = function(){
var bullet;
//here we instantiate a bullet and fire it
console.log("begin fire");
bullet = new bullet();
console.log("created bullet to fire");
}
}
因此,在 JS 中,所有变量声明都会移至当前函数作用域的顶部。请注意,并非所有编程语言都是如此。在某些语言中,您可以摆脱上述情况,并且 bullet
变量将成功替换 bullet
函数。
最好的解决方案是为变量指定不同的名称。
function gun(){
//state for the gun, amount of bullets and sort
console.log("gun created");
this.fire = function(){
//here we instantiate a bullet and fire it
console.log("begin fire");
var mybullet = new bullet();
console.log("created bullet to fire");
}
}
此外,正如匈牙利提出的那样,我认为您误解了 JS 中的 new
运算符。
编辑:澄清提升的含义。
关于javascript - 在 JavaScript 中实例化方法中实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20275115/