引用自己的对象属性 [英] Referencing own object properties

查看:65
本文介绍了引用自己的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作是否有任何问题....

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆