javascript - 无法在 JavaScript 中创建新实例

标签 javascript html objectinstantiation

以下是我的代码,

function hostile(x, y) {
        this.speed = 1;
        this.health = 100; 
        this.x = x; 
        this.y = y; 
        this.height = 32;
        this.width = 32;
        this.isDead = false;
        this.direction = 0;

        this.move = function(){
             context.clearRect(0,0,canvas1.width,canvas1.height); 
             if (this.x > canvas.width - 64) {

                 this.y += 10;
                 this.direction = 0;
             }
             if (this.x < 0) {
                 this.y += 10;
         }

             if (this.direction === 1) {
                 this.x += this.speed;
         } else {
               this.x -= this.speed;
         }
             if (this.x < 0) {
               this.direction = 1;
             }

             if (this.y > 420) {
             //this might have to be changed
                 this.x = 600;
             }
         }  
    };
//CREATING AN INSTANCE OF HOSTILE, THIS ISN'T WORKING FOR MULTIPLE INSTANCES, BUT WHY?

var hostile = new hostile(20,20);
var hostileA = new hostile(20,20);

我创建了 hostile 并且在更新方法 hostile.move() 中调用了这个实例,但是 var hostile 可以工作,var hostile 没有,我检查了代码 hostile 是文件中的唯一引用。

最佳答案

var hostile = new hostile(20,20);

您刚刚覆盖了 hostile 变量以引用该实例而不是构造函数。

这是构造函数按照约定采用大驼峰命名的原因之一

关于javascript - 无法在 JavaScript 中创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19542854/

相关文章:

c++ - 在类中声明对象时可能会导致此错误的原因是什么?

python - 获取遗传算法中使用的对象的值

javascript - TreeView 留言板 - 禁用对 child 不起作用的提交按钮

javascript - 使用 javascript 提交表单数据(无需重新加载页面)

javascript - 一个滑动,延迟然后自动滑出的弹出窗口

java - java如何隐式创建对象?就像 String 类的情况一样

javascript - 第一次播放后,循环中的howler js音量 slider 不起作用

Javascript -> 热键 -> 禁用输入字段

javascript - Ember css 不起作用 + 如何创建两个样式表

html - 显示 CSS : some divs fixed, 一些灵活的 (2)