引用自己的对象属性 [英] 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();
这是以这种方式创建类时引用对象属性的最佳方式(即调用来自setStatus函数的myObject.name?
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)?
推荐答案
看起来你知道当这时.setStatus
触发上下文变量此
将引用收到该事件的元素(即您的< body>
)而不是 myObject
。
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
.
但是你真的不应该参考<对象本身内的code> 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.
要解决您可以将此
作为附加参数传递给 .mouseMove
因此:
To resolve that you can pass this
as an additional parameter to .mouseMove
thus:
$("body").mousemove(this, this.setStatus);
然后在您的事件处理程序中,您可以通过事件的 data
字段:
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>");
}
这篇关于引用自己的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!