开发者

Object Notation in Javascript

I'm trying to call a blur function on a variable assigned to a jquery object (an input field). How do I call the function on the variable?

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");  
      }); 



    }
}

I have also tried -

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

Any help would be appreciated! thanks


UPDATE:

My previous answer was incorrect, as you can access properties of your object from a member function using this. The situation that I was describing is different. You wouldn't be able to do this, for example:

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

But yours is fine. In fact, as noted in your comment below, the problem turned out to be that someObject.init() was called from outside document.ready().


Previous answer:

Yes, you cannot refer to a property of an object before the object is initialized1. You may want to consider using the Module Pattern (a.k.a. the Yahoo Module Pattern) as a solution:

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜