无法在javascript中创建新实例

时间:2013-10-23 13:20:42

标签: javascript html5 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是文件中唯一的引用。

2 个答案:

答案 0 :(得分:2)

var hostile = new hostile(20,20);

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

这是构造函数按惯例为UpperCamelCase的原因之一

答案 1 :(得分:1)

您正在使用

删除构造函数
var hostile = new hostile(20,20);

然后你无法创建其他敌对对象。