[英]Object literal JavaScript pattern not identifying object variables
I am trying to create a javascript game using sockets, but I'm getting stuck at the OOP of my objects. 我正在尝试使用套接字创建一个JavaScript游戏,但是我陷入了对象的OOP问题。 I am having a problem referencing an object's variables from inside the object's function.
我在从对象的函数内部引用对象的变量时遇到问题。
There could be several problems here. 这里可能有几个问题。 I am calling the draw function from within the object and not a render function.
我正在从对象内部调用draw函数,而不是从render函数调用。 I am also not sure if the object literal design is done correctly.
我也不确定对象文字设计是否正确完成。
Using Require.js and class.js, we have User.js : 使用Require.js和class.js,我们有了User.js:
define(['entity'],function(Entity){
var User = Entity.extend({
init: function(){
this.health= 10;
},
draw: function(ctx){
img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here
ctx.drawImage(img, this.posx, this.posy);
};
img.src = '/images/object.PNG'; // Set source path
}
})
return User;})
extending from Entity.js 从Entity.js扩展
define(function(){
var Entity= Class.extend({
init: function(){
//object image
this.img.src = '/images/Blue-soldier.PNG';
//location
this.posx=50;
this.posy=50;
//gameplay values
this.health=1;
this.speed=0;
},
User.draw(ctx) is called in game.js : 在game.js中调用User.draw(ctx):
var entity = new User;
this.users.push(entityid);
entity.draw(ctx);
},
This.posx and this.posy are not recognized in user.draw(). 在user.draw()中无法识别this.posx和this.posy。 When they are replaced with hard values, it works fine.
当用硬值替换它们时,它可以正常工作。 What am i missing?
我想念什么?
My complete code is a little more confusing, but you can find it at https://github.com/mtbarta/canvas/blob/master/public/javascripts/client.js 我的完整代码有些混乱,但是您可以在https://github.com/mtbarta/canvas/blob/master/public/javascripts/client.js上找到它
Thanks! 谢谢!
The problem is that you're trying to use this
in the "load" handler, where the value will not be what it is in the "draw" function. 问题是您试图在“加载”处理程序中使用
this
,该值将不是“绘制”函数中的值。 Try this: 尝试这个:
var entity = this;
img.onload = function(){
// execute drawImage statements here
ctx.drawImage(img, entity.posx, entity.posy);
};
By preserving a copy of this
in the local variable "entity", the handler will have access to it. 通过保存的副本
this
局部变量“实体”,该处理器将有机会获得它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.