Skip to content Skip to sidebar Skip to footer

Referencing Own Object Properties

Is there any issue doing the following.... var myObject = { name: 'Johnny', init: function() { $('body').mousemove(this.setStatus); }, setStatus: function(e

Solution 1:

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>");
}

Solution 2:

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


Solution 3:

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>");
    }
};

Solution 4:

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


Post a Comment for "Referencing Own Object Properties"