Javascript中的对象表示法

时间:2010-08-21 12:04:50

标签: javascript jquery

我正在尝试在分配给jquery对象(输入字段)的变量上调用blur函数。如何在变量上调用函数?

var someObject = {
    day: $('#dayInputField'), // input text field

    init:function(){
       console.log("this.day" + this.day); // outputs object
       this.validateField();

    },
    validateField : function(){

      //this gets triggered - but I need to reference the variable
      $('#dayInputField').blur(function(){
       console.log("This gets triggered");
      };

      // this doesn't get triggered - how do I target the variable? 

      this.day.blur(function(){
        console.log("doesn't work");  
      }); 



    }
}

我也试过了 -

$(this.day).blur
$(this).day.blur 
someObject.day.blur
$(day, this).blur 

任何帮助将不胜感激! 谢谢

1 个答案:

答案 0 :(得分:1)

<强>更新

我以前的回答是不正确的,因为可以使用this从成员函数访问对象的属性。我描述的情况不同。你无法做到这一点,例如:

var someObject = {
   day: 'some value',
   day2: day
};

但是你的很好。事实上,正如您在下面的评论中所指出的,问题是someObject.init()来自外部document.ready()


上一个回答:

是的,在初始化对象 1 之前,不能引用对象的属性。 你可能想考虑使用Module Pattern(a.k.a.雅虎模块模式)作为解决方案:

var someObject = (function () {
   var day = $('#dayInputField');

   return {
      init: function () {
         console.log("this.day" + this.day); // outputs object
         this.validateField();   
      },

      validateField: function () {    

         //this gets triggered - but I need to reference the variable
         $('#dayInputField').blur(function(){
            console.log("This gets triggered");
         };

         // now this doesn get triggered
         day.blur(function(){
            console.log("it works");  
         }); 
      }
   };
})();

// Use someObject as you were doing before:
someObject.init();
someObject.validateField();

1 Stack Overflow:How can a Javascript object refer to values in itself?