Javascript:如何从事件回调函数访问对象成员
我在试图找出我的对象设计出了什么问题时遇到了一些问题。
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() 函数。
所以,这就是我不明白的地方: * 什么时候使用“this”是安全的?从reply_to()使用它却不是,因为上下文似乎被设置为调用者元素。 * 为什么我可以从reply_to调用“set_text()”,但无法访问“textarea”成员? * 我应该如何从reply_to()(这是一个事件回调)访问“textarea”成员?
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.
}
};
}();
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.
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于在这些处理程序内部,上下文会发生变化,因此保留对所需上下文的引用是最简单的,我个人更喜欢
self
。这是一种替代格式:您可以在此处测试。诚然,尽管我不太确定您想要实现什么目标。您正在尝试返回
reply_to
函数,但自己将其绑定在init()
就绪处理程序中...因此您可以立即绑定它(如上所示),或者更改它并返回您想要在其他地方绑定的内容。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: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 theinit()
ready handler...so you can either bind it immediately (like above), or change it up and return what you want to bind elsewhere.