gpt4 book ai didi

javascript - JS 类的多个实例

转载 作者:行者123 更新时间:2023-11-28 20:18:31 26 4
gpt4 key购买 nike

我在 JavaScript 中得到了以下“Enemy”类:

function Enemy(position, rotation) {
this.name = null;

this.enemyForm = new Kinetic.Rect({
x: 0,
y: 0,
width: 20,
height: 20,
fill: 'red',
stroke: 'black',
strokeWidth: 1
});
this.setX(position.posX);
this.setY(position.posY);
this.setRotation(rotation);
this.setOffset(10, 10);
this.add(this.enemyForm);
}

Enemy.prototype = new Kinetic.Group();

如您所见,我为此扩展了一个 Kinetic.Group,因为敌人将拥有更多的动能元素,而不仅仅是一个矩形。

现在我创建该“类”的一些实例并将它们添加到游戏层:

 var enemy1 = new Enemy({posX: 50, posY: 50}, 0);
this.layer.add(enemy1);
var enemy2 = new Enemy({posX: 100, posY: 100}, 0);
this.layer.add(enemy2);
var enemy3 = new Enemy({posX: 200, posY: 200}, 0);
this.layer.add(enemy3);

问题:每个敌人都获得“enemy3”的位置,而不是他们自己的位置。因此,每个敌人都会被绘制在位置“200, 200”。现在,如果我在没有继承的情况下尝试这个,它工作得很好:

function Enemy(position, rotation) {
this.name = null;
this.enemyForm = new Kinetic.Group();

var rect = new Kinetic.Rect({
x: 0,
y: 0,
width: 20,
height: 20,
fill: 'red',
stroke: 'black',
strokeWidth: 1
});
this.enemyForm.setX(position.posX);
this.enemyForm.setY(position.posY);
this.enemyForm.setRotation(rotation);
this.enemyForm.setOffset(10, 10);
this.enemyForm.add(rect);
}

谁能告诉我我缺少什么,以及为什么我没有用第一种方法获得单独的对象?

最佳答案

子类化 Kinetic.Group 没有问题:

// a bunch of code from 
// http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.6.0.min.js

//optionally a config object can be passed to the constructor
//http://kineticjs.com/docs/Kinetic.Group.html
var Test = function(config){
Kinetic.Group.call(this,config);
};
Test.prototype=Object.create(Kinetic.Group.prototype);

var test = new Test();

for(s in test){
console.log(s);
}

关于javascript - JS 类的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18801776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com