prototype如何在JavaScript中工作?

prototype如何在JavaScript中工作?,javascript,html,Javascript,Html,我刚刚开始了一个使用JavaScript和HTML5的游戏开发教程。javascript.prototype已经发挥了很多作用。我真的不明白它是怎么工作的。这里有一个链接,我找到了一个很好的解释,但我仍然有点困惑 有人能解释一下吗? 下面是我的代码示例: function Enemy(){ this.srcX = 140; //gets the location of enemy in x and Y here this.srcY = 600;

我刚刚开始了一个使用JavaScript和HTML5的游戏开发教程。javascript.prototype已经发挥了很多作用。我真的不明白它是怎么工作的。这里有一个链接,我找到了一个很好的解释,但我仍然有点困惑

有人能解释一下吗? 下面是我的代码示例:

 function Enemy(){
        this.srcX = 140;  //gets the location of enemy in x and Y here
        this.srcY = 600;
        this.width = 45;//gets the enemies width and height here
        this.height = 54; 
        this.drawX = randomRange(0, canvasWidth  - this.width);
        this.drawY = randomRange(0, canvasHeight - this.height); 
        this.centerX = this.drawX + (this.width / 2);
        this.centerY = this.drawY +(this.height / 2);

        //this.targetX = this.centerX;
        //this.targetY = this.centerY;
        //this.randomMoveTime = randomRange(4000,10000);
        this.speed = 1;
        //var that = this;
        //this.moveInterval = setInterval(function() {that.setTargetLocation();},that.randomMOveTime);
        this.isDead = false;
    }

    Enemy.prototype.update = function() {
        //this.checkDirection();
         this.centerX = this.drawX + (this.width / 2);
        this.centerY = this.drawY + (this.height / 2);
    }

我认为关于原型继承的最大困惑是,对象通过其内部
[[prototype]]
属性从其构造函数的原型继承。两者都被称为“原型”。所有函数都有一个默认的原型属性,该属性为空对象

就你而言:

function Enemy(){
        this.srcX = 140;  //gets the location of enemy in x and Y here
        this.srcY = 600;
        ...
}
是一个函数,当使用new调用时,它充当一个构造函数,将属性分配给自身的新实例。该实例具有指向敌方.Prototype的内部
[[Prototype]]
属性

然后:

这会将一个新属性指定给作为函数的敌方.prototype。因此,这将更新属性放在所有敌人实例的继承链上,因此它们都继承一个更新方法

因此:

只有当两个表达式引用同一个对象(即分配给敌方.prototype.update的函数)时,测试才能为真

您可以继续将属性和方法添加到敌方.prototype,所有实例都将继承这些属性和方法,即使是已经构建的实例。但如果将其更改为其他对象:

Enemy.prototype = {update:function(){/*new update function*/}};
然后旧实例仍将具有旧的
[[Prototype]]
,而新实例将具有新实例


web上有一百万篇关于javascript原型继承的文章,请阅读并使用它,如果有的话,请询问更多问题。:-)

魔法。严肃地说,它的字面意思是“所有敌人的物体都会有一个
update
功能”,“但我还是有点困惑”到底是什么?从另一个问题的答案中你到底不明白什么?如果我告诉你,
new defey()
大致相当于
var newObj=Object.create(敌方.prototype)),这有帮助吗;应用(newObj,参数);返回newObj?@FelixKling我完全理解,我只是不理解原型
敌人之后的udpate部分。原型
是一个对象<代码>敌方.prototype.update=函数(){…}将一个函数指定给该对象的
update
属性。由于该属性尚不存在,因此将创建它。更简单的例子:
var foo={};foo.bar=function(){console.log('hi');};foo.bar()。这与原型无关。这就是JavaScript中对象的工作方式@FelixKling在本例中,我们正在为敌人对象创建更新属性。它与我拥有的另一个叫做update的函数无关
var enemy0 = new Enemy();
var enemy1 = new Enemy();

typeof enemy0.update // function
typeof enemy1.update // function

enemy0.update === enemy1.update  // true
Enemy.prototype = {update:function(){/*new update function*/}};