Johnny Rambo
Johnny Rambo

Reputation: 233

Referencing own object properties

Is there any issue doing the following....

var myObject = {
    name: "Johnny",
    init: function() {
        $("body").mousemove(this.setStatus);
    },
    setStatus: function(ev) {
        $("body").append("<div>Mouse Move by: " + myObject.name + "</div>");
    }
};

myObject.init();

Is this the best way of referencing an object's property when a class is created in this way (i.e. calling myObject.name from the setStatus function)?

Upvotes: 4

Views: 182

Answers (4)

Alnitak
Alnitak

Reputation: 339796

It looks like you're aware that when this.setStatus is triggered the context variable this will refer to the element that received the event (i.e. your <body>) rather than to myObject.

However you really shouldn't refer to myObject within the object itself - an object should have no knowledge of what it's being called outside of itself.

To resolve that you can pass this as an additional parameter to .mouseMove thus:

$("body").mousemove(this, this.setStatus);

and then within your event handler you can retrieve your current object reference via the event's data field:

setStatus: function(ev) {
    var self = ev.data;
    $("body").append("<div>Mouse Move by: " + self.name + "</div>");
}

Upvotes: 2

punkrockbuddyholly
punkrockbuddyholly

Reputation: 9794

That way is fine. Another way of doing it would be to just pass an anonymous function to the mousemove:

var myObject = {
    name: "Johnny",
    init: function() {
        var thisObject = this;
        $("body").mousemove(function() {
            $("body").append("<div>Mouse Move by: " + thisObject.name + "</div>");
        });
    }
};

myObject.init();

See fiddle

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318488

You need to ensure that the this is still available. When passing the function to an event handler, this will point to the related DOM node.

Since you are using jQuery, you can use $.proxy() to bind this inside the function to something else:

$("body").mousemove($.proxy(this.setStatus, this));

However, it would be cleaner to make the original this available by other means:

var myObject = {
    name: "Johnny",
    init: function() {
        var self = this;
        $("body").mousemove(function(ev) {
            self.setStatus.call(this, ev, self);
        });
    },
    setStatus: function(ev, self) {
        $("body").append("<div>Mouse Move by: " + self.name + "</div>");
    }
};

Upvotes: 0

Mariy
Mariy

Reputation: 5914

This is perfectly fine. If setStatus isn't used anywhere else, you can move it to an anonymous function and pass it to mousemove.

Upvotes: 1

Related Questions