1 Reply Latest reply on Sep 20, 2010 9:13 AM by Marc Autret

    Undefined is not an object

    Barqx Level 1

      I have the following extract from my code:

      function foo()
      {
      [...]
      Dlg.gMain[caption].gPageItems.gPhoto.molgrew = Dlg.gMain[caption].gPageItems.gPhoto.add('group',undefined);
      Dlg.gMain[caption].gPageItems.gPhoto.molgrew.cb = Dlg.gMain[caption].gPageItems.gPhoto.molgrew.add('checkbox',undefined,undefined);
      alert("1 = " + caption + " 2 = " + molgrew);
      }
      
      function bar()
      {
      Dlg.gMain[pageType].gPageItems.gPhoto.caption.cb = Dlg.gMain[pageType].gPageItems.gPhoto.caption.add('checkbox',undefined,undefined);  
      alert("1 = " + pageType + " 2 = " + caption);
      }
      
      foo();
      bar();
      
      

       

      The two alerts are exactly identical. However, I get the error: "Undefined is not an object" in function bar()

       

      When checking the types of the references Dlg.gMain[pageType].gPageItems.gPhoto.caption is undefined. I have no explanation as to why that is.

       

      Cane someone help me out, please?

        • 1. Re: Undefined is not an object
          Marc Autret Level 4

          Assuming that:

           

          (1) Dlg is a global variable,

          (2) caption and molgrew are known within foo(),

          (3) pageType and caption are known within bar(),

          (4) Dlg.gMain[caption].gPageItems.gPhoto refers to an existing object (in foo),

          (5) Dlg.gMain[pageType].gPageItems.gPhoto refers to an existing object (in bar),

           

          the error message you get simply indicates that the caption property is not defined in the Dlg.gMain[pageType].gPageItems.gPhoto object, and indeed your code does not show any statement which lets suppose that Dlg.gMain[pageType].gPageItems.gPhoto.caption is defined, so you cannot create the property Dlg.gMain[pageType].gPageItems.gPhoto.caption.cb.

           

          FYI, JavaScript does not allow you to create a 'chain of properties' in one line:

           

          //---------------------------------

          // The following code will throw
          // "Undefined is not an object!"
          // because obj.prop is not defined

          //---------------------------------
          var obj = {};
          obj.prop.subprop = 'wrong!';

           

           

          //---------------------------------

          // You HAVE to do something

          // like this:

          //---------------------------------

          var obj = {};
          obj.prop = {};
          obj.prop.subprop = 'right!';

           

          @+

          Marc

           

          EDIT: However the JSON syntax allows you to create a complex object this way:

          var obj = { prop: { subprop: 'right!' } };