Leo Jiang
Leo Jiang

Reputation: 26085

Passing objects to jQuery methods

function unit(){
    this.html=$('<div></div>');
    this.html.click(this,function(e){
        e.data.move(e.data.x,e.data.y);
    });
}

$('#factory').click(function(){
    unit();
}

I'm attempting to learn OOP in Javascript. Here's a "class" for a unit in a war game that I made for practice. Each time the factory is clicked, a new unit is created. However, when I click on an old unit to move it, the newest unit is always the one that moves. So basically, e.data always corresponds to the newest unit, not the one which was clicked. How do I make it so that e.data always corresponds to the unit which was clicked?

Upvotes: 1

Views: 40

Answers (1)

the system
the system

Reputation: 9336

this is a reference to window if you don't use new to invoke unit();. The way it is right now, you're overwriting window.html every time you click.

To create a new object and make this reference that object, do:

new unit();

Upvotes: 2

Related Questions