Javascript:如何从事件回调函数访问对象成员 [英] Javascript: How to access object member from event callback function

查看:121
本文介绍了Javascript:如何从事件回调函数访问对象成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题想要弄清楚我的对象设计有什么问题。

I have some problems trying to figure out what is wrong with my object design.

var comment = function(){
var textarea = null;
$(document).ready( init );

function init()
{
    $('.reply').click( comment.reply_to );
    this.textarea = $('.commentbox textarea');
    console.log( this.textarea );   // properly shows the textarea element
    console.log( textarea );        // outputs null
}

function set_text( the_text )
{
    console.log( textarea );        // outputs null
    console.log( this.textarea );   // outputs undefined
    textarea.val( the_text );
}

return {
    reply_to: function()
    {
        console.log( this );            // outputs the element who fired the event
        set_text( 'a test text' );      // properly gets called.
    }
};
}();

当文档完全加载时,init()会自动调用并初始化对象。我必须注意,textarea成员正确地指向所需的元素。
一个点击事件被附加到一个回复按钮,因此,当用户点击它时调用reply_to()函数。

When document is fully loaded, init() is automatically called and initializes the object. I must note that the textarea member properly points to the desired element. A click event is attached to a "reply" button, so reply_to() function is called whenever user clicks on it.

不明白:
*当使用this是安全的吗?使用它从reply_to()它不是,因为它似乎上下文设置为调用者元素。
*为什么我可以从reply_to调用set_text(),但是我不能访问textarea成员?
*我应该如何从reply_to()访问textarea成员(这是一个事件回调)?

So, this is what I don't understand: * When using "this" is safe? Using it from reply_to() it is not, as it seems like the context is set to the caller element. * Why I can call "set_text()" from reply_to, but I cannot access the "textarea" member? * How I should do to access "textarea" member from reply_to() (which is an event callback)?

推荐答案

p>因为在这些处理程序中,上下文将改变,最容易引用你想要的上下文,我个人更喜欢 self 。这里有一种替代格式:

Since inside those handlers the context will change, it's easiest to keep a reference to the context you want, I personally prefer self. Here's one alternative format:

var comment = function(){
    this.textarea = null;
    var self = this;
    $(document).ready( init );

    function init()
    {
        $('.reply').click( reply_to );
        self.textarea = $('.commentbox textarea');
    }

    function set_text( the_text )
    {
        self.textarea.val( the_text );
    }

    function reply_to() {
      set_text( 'a test text' );
    }
}();

您可以在这里测试。诚然,虽然我不是真的确定你想要完成,但。您试图返回 reply_to 函数,但自己绑定在 init()就绪处理程序...中你可以立即绑定它(如上),或更改它,并返回你想绑定到别处。

You can test it here. Admittedly though I'm not really sure what you're trying to accomplish though. You are trying to return the reply_to function, but bind it yourself inside the init() ready handler...so you can either bind it immediately (like above), or change it up and return what you want to bind elsewhere.

这篇关于Javascript:如何从事件回调函数访问对象成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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