【发布时间】:2010-12-03 09:48:18
【问题描述】:
我在试图找出我的对象设计出了什么问题时遇到了一些问题。
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”成员(这是一个事件回调)?
【问题讨论】:
标签: javascript jquery callback object