寻找一些非常快速的帮助,
contactForm={
that: this,
lilfield: 'I just equal this',
fields: new Array("hc_name","hc_email","hc_telephone"),
submit_button: jQuery("#hc_submit"),
init: function(){
that.lilAlert();
},
lilAlert: function(){
alert("lets pump this out");
}
}
以上只是一个例子,但实际上我想要实现的是可用于继续调用而不是引用对象'contactForm'本身的变量。这也比使用它更安全一些,因为在jQuery等点击等事件上自动传递它。
答案 0 :(得分:1)
两件事。
that
指向创建的this
contactForm,不是实际的contactForm。that
是联系表单的属性,因此您需要通过this.that
或contactForm.that
访问它,这样做会破坏最初的目的。或者:
或在需要它的函数中定义that
init: function(){
var that = this;
that.lilalert();
}
如果您只想避免this
恶作剧,那么另一种选择是使用闭包(因此使用词法,静态范围代替通过this
进行动态绑定)
function make_contact_form(){
var lilfield: 'I just equal this';
var fields = ["hc_name","hc_email","hc_telephone"]; //dont use new Array. its evil
var submit_button = jQuery("#hc_submit");
var init = function(){
lilAlert(); //lilAlert is a name is scope. call it directly
};
var lilAlert = function(){
alert("lets pump this out");
};
return {
lilfield: lilfield,
fields: fields,
submit_button: submit_button,
init: init,
lilAlert: lilAlert
};
}
答案 1 :(得分:0)
你太复杂了;只需拨打this.lilAlert()
即可,只要您在<{1}} 上呼叫init()
,就可以正常工作。
contactForm
contactForm.init(); // this will work;