javascript - 在 JavaScript 中实例化方法中实例化对象

标签 javascript oop

我正在尝试使用 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/

相关文章:

javascript - 将值从输入传递到返回对象的构造函数

javascript - 检测 HTML 链接是否被点击

javascript 函数未定义错误。句法?

c# - 如何创建完美的 OOP 应用程序

java - 这个先决条件是否违反了里氏替换原则

c# - 从父类(super class) C# 返回子类的 "this"

objective-c - Objective-C 装饰器模式的简单实现

javascript - 为什么 ECMASCRIPT 6 在解构时反转分配的边?

javascript - 如何修复 "My first scan value is not same as my second scan value and the value scan in HTML is not same as value scan in notepad?"

javascript - 格式化数组以在 node.js 中输出