Link to the object’s own properties

Is there a problem that does 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 to reference an object property when the class is created this way (i.e. by calling myObject.name from the setStatus function)?

+4
source share
4 answers

It looks like you know that when triggered, the this.setStatuscontext variable thiswill refer to the element that received the event (i.e. yours <body>), and not to myObject.

However, you really should not refer to the myObjectinside of the object itself - the object should not know that it is being called outside of itself.

To decide what you can pass thisas an extra parameter .mouseMove, this way:

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

data:

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

. setStatus , mousemove.

+1

, this - . this DOM node.

jQuery, $.proxy() this - :

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

this :

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

. - mousemove:

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

myObject.init();

. fiddle

0

All Articles