finding the type of an object? ("typeof" doesn't work)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bennett Haselton

    finding the type of an object? ("typeof" doesn't work)

    Is there any way to find a string representing an object's class,
    which will work in Internet Explorer 6?

    "typeof" doesn't work -- it returns "object" for all objects:

    x = window.open('ht tp://www.yahoo.com/');
    alert(typeof x);

    And I found this page:

    which claims: "To get the type of an object x, use x.class".

    However, that doesn't work in IE 6 so it must be Mozilla-only.

    Can it be done?

    -Bennett
  • Martin Honnen

    #2
    Re: finding the type of an object? ("typeof&q uot; doesn't work)



    Bennett Haselton wrote:
    [color=blue]
    > Is there any way to find a string representing an object's class,
    > which will work in Internet Explorer 6?
    >
    > "typeof" doesn't work -- it returns "object" for all objects:
    >
    > x = window.open('ht tp://www.yahoo.com/');
    > alert(typeof x);[/color]

    Well, JavaScript 1.x doesn't have classes so I am not sure what you are
    looking for. In terms of JavaScript/ECMAScript edition 3 x is of type
    Object.


    --

    Martin Honnen


    Comment

    • Fox

      #3
      Re: finding the type of an object? ("typeof&q uot; doesn't work)



      Bennett Haselton wrote:[color=blue]
      >
      > Is there any way to find a string representing an object's class,
      > which will work in Internet Explorer 6?
      >
      > "typeof" doesn't work -- it returns "object" for all objects:
      >
      > x = window.open('ht tp://www.yahoo.com/');
      > alert(typeof x);
      >
      > And I found this page:
      > http://www.mozilla.org/js/language/j...pressions.html
      > which claims: "To get the type of an object x, use x.class".[/color]

      You can't do this yet -- .class is a proposed addition for JS2
      [color=blue]
      >
      > However, that doesn't work in IE 6 so it must be Mozilla-only.
      >
      > Can it be done?[/color]

      Not for window or document -- not in IE.

      Normally, you would parse the constructor, but window.construc tor and
      document.constr uctor are both "undefined" in IE (it's not JavaScript -
      it's JScript). In Mozilla, the constructors are returned as "[Window]"
      and "[HTMLDocument]" {*not* function Window(...etc.. . as a "regular"
      JavaScript constructor} Furthermore, in IE, window and document are
      synonymous (but not exactly equal to each other).

      proof:

      alert( window == document );

      // IE => true; Moz => false


      Considering that you cannot instantiate a Window or Document object from
      within JavaScript, it really doesn't matter one way or the other.


      for all other javascript objects:

      Object.prototyp e.objectType = function()
      {
      var obType = String(this.con structor).match (/function\s+(\w+ )/);

      if(obType) return obType[1];
      return "undefined" ; // just in case...
      }


      examples:

      function
      _myObject()
      {
      this.anything=" ";
      }

      var mo = new -myObject();

      alert(mo.object Type()); // type => _myObject

      some others (as literals)

      alert( (123).objectTyp e()); // => Number

      alert( ([1,2,3]).objectType()) ; // => Array

      alert( ("123").objectT ype()); // => String

      alert( (true).objectTy pe()); // => Boolean

      and:

      function
      myFunc()
      {
      var nada = "";
      }

      alert( myFunc.objectTy pe() ); // => Function

      etc...


      if this isn't what you meant... then never mind...

      Comment

      • Jim Ley

        #4
        Re: finding the type of an object? ("typeof&q uot; doesn't work)

        On Sun, 02 May 2004 22:43:28 -0500, Fox <fox@fxmahoney. com> wrote:
        [color=blue]
        >Normally, you would parse the constructor, but window.construc tor and
        >document.const ructor are both "undefined" in IE (it's not JavaScript -
        >it's JScript).[/color]

        They're host objects, so the language is irrelevant. You get the same
        behaviour in DScript, and if anyone packaged up SpiderMonkey as an
        ActiveScripting language you would there to.
        [color=blue]
        > Furthermore, in IE, window and document are
        >synonymous (but not exactly equal to each other).
        >
        >proof:
        >
        >alert( window == document );
        >
        >// IE => true; Moz => false[/color]

        That they get type converted to something that == each other in IE is
        not proof that they are synonymous.
        [color=blue]
        >Considering that you cannot instantiate a Window or Document object from
        >within JavaScript, it really doesn't matter one way or the other.[/color]

        Indeed!

        Jim.
        --
        comp.lang.javas cript FAQ - http://jibbering.com/faq/

        Comment

        • Thomas 'PointedEars' Lahn

          #5
          Re: finding the type of an object? (&quot;typeof&q uot; doesn't work)

          Bennett Haselton wrote:
          [color=blue]
          > Is there any way to find a string representing an object's class,
          > which will work in Internet Explorer 6?[/color]

          No, since ECMAScript up to ed. 3 and thus JavaScript up to version 1.5
          and JScript up to version 5.6 do not provide a class-based object model
          but a prototype-based one.
          [color=blue]
          > "typeof" doesn't work --[/color]

          It does.
          [color=blue]
          > it returns "object" for all objects:[/color]

          As it is supposed to.
          [color=blue]
          > x = window.open('ht tp://www.yahoo.com/');[/color]

          Have you declared the variable previously? If not, you better use the
          `var' keyword here.
          [color=blue]
          > alert(typeof x);
          >
          > And I found this page:
          > http://www.mozilla.org/js/language/j...pressions.html
          > which claims: "To get the type of an object x, use x.class".[/color]

          ECMAScript 4 is yet to be standardized and JavaScript 2.0 to be the base
          of it is yet to be implemented in UAs. If you would have read the above
          thoroughly you would have noticed that there is still only one
          implementation of ECMAScript 4 available -- Epimetheus. (Which could
          become a prophetical choice since it is entirely possible that ECMAScript
          4/JavaScript 2.0 will never be finished as AOLTW had temporarily closed the
          Netscape browser division recently and, as probably a result, Netscape is
          no longer a member of ECMA.)
          [color=blue]
          > However, that doesn't work in IE 6[/color]

          IE resp. the Windows Script Host supports, among other script languages
          like VBScript, JScript -- Microsoft's implementation of ECMAScript up to
          ed. 3. So a JavaScript spec/doc is simply the wrong place to look, no
          matter how current it is.
          [color=blue]
          > so it must be Mozilla-only.[/color]

          It does not work in current Mozillas either.
          [color=blue]
          > Can it be done?[/color]

          That depends on what you are looking for and where. In ECMAScript 3 and
          thus JavaScript 1.5 each object has a "constructo r" property (inherited
          from the Object prototype) referring to the constructor used to create the
          object. Since that constructor function (in fact, *every* named function
          statement) is also the definition for an object prototype, objects created
          using the Foo() constructor can be referred to as "Foo objects".
          window.open() returns a reference to a Window object if successful. One
          could test for this in Gecko-based UAs with

          if (x && x.constructor && x.constructor == Window)
          {
          // ...
          }

          But since window.open() never returns an object of a type different
          from Window if successful and not every UA provides a public prototype
          for all of its host objects (as Window objects are), that test appears
          to be only academical. AFAIK

          if (x)
          {
          // ...
          }

          always sufficed to date. If there are statements between the
          window.open() call and the test, the latter should be changed to

          if (x && !x.closed)
          {
          // ...
          }

          Both solutions have been pointed out to numerous times in this newsgroup
          before. Please search before you post, see the FAQ.


          PointedEars

          Comment

          • Lasse Reichstein Nielsen

            #6
            Re: finding the type of an object? (&quot;typeof&q uot; doesn't work)

            Thomas 'PointedEars' Lahn <PointedEars@nu rfuerspam.de> writes:
            [color=blue]
            > Bennett Haselton wrote:
            > If you would have read the above thoroughly you would have noticed
            > that there is still only one implementation of ECMAScript 4
            > available -- Epimetheus.[/color]

            I believe JScript.NET is also a (perhaps partial) implementation of
            ECMAScript v4.
            [color=blue]
            > That depends on what you are looking for and where. In ECMAScript 3 and
            > thus JavaScript 1.5 each object has a "constructo r" property (inherited
            > from the Object prototype) referring to the constructor used to create the
            > object.[/color]

            The constructor isn't necessarily inherited. When a user declared
            function is created, its prototype object is also created and assigned
            to the function's "prototype" property. After that, the function is
            assigned to the prototype object's "constructo r" property.
            I.e.,
            function foo(){};
            also creates the new object
            foo.prototype
            and makes the assignment
            foo.prototype.c onstuctor = foo;

            In this case, the constructor property is not inherited.

            In the case of host objects, all bets are off, as usual. In my
            browser, Opera, it is correct that window.constuct or is inherited (it
            is Object). In Mozilla, where there are available constructors for
            most host objects, window.construc tor is the global function Window.
            [color=blue]
            > Since that constructor function (in fact, *every* named function
            > statement) is also the definition for an object prototype, objects created
            > using the Foo() constructor can be referred to as "Foo objects".[/color]

            Yes, as long as one makes sure not to break the relationship by manually
            manipulating prototypes.
            ---
            function Foo(){ this.x = 42; }
            function Bar(){ this.y = 37; };
            var foo = new Foo();
            var bar = new Bar();
            alert([foo instanceof Foo,
            foo instanceof Bar,
            bar instanceof Foo,
            bar instanceof Bar]); // true,false,true ,false
            // swap:
            var fprot = Foo.prototype;
            Foo.prototype = Bar.prototype;
            Bar.prototype = fprot;
            Foo.prototype.c onstructor = Foo;
            Bar.prototype.c onstructor = Bar;
            // and they are swapped.
            alert([foo instanceof Foo,
            foo instanceof Bar,
            bar instanceof Foo,
            bar instanceof Bar]); // false,true,fals e,true
            ---
            The connection between an object and its constructor is really a connection
            between the object and the constructor function's prototype object, because
            inhertance happens between objects. The constructor functions merely
            facilitate the creation and initialization of new objects based on an
            old object.

            /L
            --
            Lasse Reichstein Nielsen - lrn@hotpop.com
            DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
            'Faith without judgement merely degrades the spirit divine.'

            Comment

            • Thomas 'PointedEars' Lahn

              #7
              Re: finding the type of an object? (&quot;typeof&q uot; doesn't work)

              Lasse Reichstein Nielsen wrote:
              [color=blue]
              > Thomas 'PointedEars' Lahn <PointedEars@nu rfuerspam.de> writes:[color=green]
              >> If you would have read the above thoroughly you would have noticed
              >> that there is still only one implementation of ECMAScript 4
              >> available -- Epimetheus.[/color]
              >
              > I believe JScript.NET is also a (perhaps partial) implementation of
              > ECMAScript v4.[/color]

              Indeed!

              <http://msdn.microsoft. com/library/default.asp?url =/library/en-us/jscript7/html/jsgrpecmafeatur es.asp>
              [color=blue][color=green]
              >> That depends on what you are looking for and where. In ECMAScript 3 and
              >> thus JavaScript 1.5 each object has a "constructo r" property (inherited
              >> from the Object prototype) referring to the constructor used to create the
              >> object.[/color]
              >
              > The constructor isn't necessarily inherited. When a user declared
              > function is created, its prototype object is also created and assigned
              > to the function's "prototype" property. After that, the function is
              > assigned to the prototype object's "constructo r" property.
              > I.e.,
              > function foo(){};
              > also creates the new object
              > foo.prototype
              > and makes the assignment
              > foo.prototype.c onstuctor = foo;[/color]

              There is an "r" missing.
              [color=blue]
              > In this case, the constructor property is not inherited.[/color]

              Sorry, I fail to see the difference.
              [color=blue][color=green]
              >> Since that constructor function (in fact, *every* named function
              >> statement) is also the definition for an object prototype, objects created
              >> using the Foo() constructor can be referred to as "Foo objects".[/color]
              >
              > Yes, as long as one makes sure not to break the relationship by manually
              > manipulating prototypes.[/color]

              There are always ways to meddle with the defined workings of the object
              model. Taking every possible way into account every time one posts a
              followup/reply would by far extend the purpose of this newsgroup.
              [color=blue]
              > ---
              > function Foo(){ this.x = 42; }
              > function Bar(){ this.y = 37; };
              > var foo = new Foo();
              > var bar = new Bar();
              > alert([foo instanceof Foo,
              > foo instanceof Bar,
              > bar instanceof Foo,
              > bar instanceof Bar]); // true,false,true ,false
              > // swap:
              > var fprot = Foo.prototype;
              > Foo.prototype = Bar.prototype;
              > Bar.prototype = fprot;[/color]

              The proper way is

              Bar.prototype = new Foo;


              <http://devedge.netscap e.com/library/manuals/2000/javascript/1.5/guide/obj2.html#10083 88>


              PointedEars

              Comment

              • Lasse Reichstein Nielsen

                #8
                Re: finding the type of an object? (&quot;typeof&q uot; doesn't work)

                Thomas 'PointedEars' Lahn <PointedEars@nu rfuerspam.de> writes:
                [color=blue]
                >
                > The proper way is
                >
                > Bar.prototype = new Foo;[/color]

                The proper way to what?
                [color=blue]
                > <http://devedge.netscap e.com/library/manuals/2000/javascript/1.5/guide/obj2.html#10083 88>[/color]

                I think this is a bad way of trying (and failing) to emulate class
                based inheritance in a non-class based language. Instead of inheriting
                from the generic class, you inherit from a single instance (which is
                what prototype based inheritance is all about). You lack the call to
                the superclass' constructor, and all your instances share the properties
                of the prototype.

                Example where it fails:
                ---
                function Stack() {
                this.stack = [];
                }
                Stack.prototype .push = function(x){thi s.stack.push(x) ;}
                Stack.prototype .pop = function(){retu rn this.stack.pop; }

                function CountableStack( ) {}
                CountableStack. prototype = new Stack();
                CountableStack. prototype.count = function() {return this.stack.leng th;}
                ---
                This looks plausible, if one reads the Netscape link above. It
                fails terribly, since all CountableStack' s use the same internal
                stack.
                ---
                var s1 = new CountableStack( );
                var s2 = new CountableStack( );
                s1.push(42);
                s2.push(37);
                alert(s1.count( ));
                ---

                So, IMO, it's *not* a propert way to do anything.

                A closer to proper way to make class-like inheritance in Javascript is
                (for Bar(x,y,z) extending Foo(x,y)):
                ---
                function Bar(x,y,z) {
                Foo.call(this,x ,y);
                this.z=z;
                }
                Bar.prototype = clone(Foo.proto type);
                ---
                where clone is
                ---
                function clone(obj) {
                function Cloner(){};
                Cloner.prototyp e = obj;
                return new Cloner();
                }
                ---
                (or *maybe* just use an instance of Foo as prototype, if you know
                that it doesn't matter that it has been initialized once).
                /L
                --
                Lasse Reichstein Nielsen - lrn@hotpop.com
                DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                'Faith without judgement merely degrades the spirit divine.'

                Comment

                Working...