Javascript对象传递自身

时间:2011-12-15 10:54:58

标签: javascript jquery javascript-objects

寻找一些非常快速的帮助,

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等点击等事件上自动传递它。

2 个答案:

答案 0 :(得分:1)

两件事。

  1. 您的that指向创建的this contactForm,不是实际的contactForm。
  2. 您的that是联系表单的属性,因此您需要通过this.thatcontactForm.that访问它,这样做会破坏最初的目的。
  3. 或者:

    1. 参考contactForm本身
    2. 或在需要它的函数中定义that

      init: function(){
          var that = this;
          that.lilalert();
      }
      

    3. 如果您只想避免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;