Using setInterval inside an object

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

    Using setInterval inside an object

    Hello =)

    I have an object which contains a method that should execute every x ms. I
    can use setInterval inside the object construct like this -

    self.setInterva l('ObjectName.m ethodName()', this.pinginterv al);

    - but is there no way to do this without using the literal ObjectName? If I
    write 'this.methodNam e()' I get "Line 1 Char 1: Object doesn't support this
    property or method." in IE, and nothing happens in Firebird.

    Thank you,
    Daniel



  • Lasse Reichstein Nielsen

    #2
    Re: Using setInterval inside an object

    "Daniel" <sorry-no-email@i-get-virus-and-spam.com> writes:
    [color=blue]
    > I have an object which contains a method that should execute every x ms. I
    > can use setInterval inside the object construct like this -
    >
    > self.setInterva l('ObjectName.m ethodName()', this.pinginterv al);
    >
    > - but is there no way to do this without using the literal ObjectName? If I
    > write 'this.methodNam e()' I get "Line 1 Char 1: Object doesn't support this
    > property or method." in IE, and nothing happens in Firebird.[/color]

    Because the "this" keyword at the time of running doesn't refer to the
    object. That is one reason to be weary about passing around code as
    strings. Passing it around as a function value keeps the textual scope,
    so the identifiers in the function refer to the ones that existed where
    the function was written, not where it is executed.

    I would write

    var myself = this;
    function callMethod() {
    myself.methodNa me();
    }
    setInterval(cal lMethod, this.pinginterv al)

    That way you don't rely on any literals being the same when the code
    is executed, but rely on the normal scope rules to keep the *value* of
    myself in the function's scope chain.

    /L
    --
    Lasse Reichstein Nielsen - lrn@hotpop.com
    Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    • Daniel

      #3
      Re: Using setInterval inside an object

      > You would need to store the object somehow in a variable that is[color=blue]
      > accessible from the code passed to setInterval
      > For example when you create objects store them in an Array
      > function AClass () {
      > this.id = AClass.instance s.length;
      > AClass.instance s[this.id] = this;
      > }
      > AClass.instance s = new Array()
      > Then in your method you script
      > setInterval('AC lass.instances[' + this.id + '].methodName();' , delay)[/color]

      I thought of this. Actually, I think you're responsible for me thinking
      this, as I think you were the one who gave me a similar approach when I
      asked about how to determine an object's run-time assigned name without
      having to store it oneself =)
      I'm gonna go with Lasse's solution, though (no offense ;), since that
      requires no manual tracking of object names.

      But thank you for your post =)

      Daniel


      Comment

      • Lasse Reichstein Nielsen

        #4
        Re: Using setInterval inside an object

        "Daniel" <sorry-no-email@i-get-virus-and-spam.com> writes:
        [color=blue]
        > PS: Er vi egentlig ikke landsmænd?[/color]

        Jo, det er vi da :)
        (and I would have answered in Danish if you had asked in the Danish
        group <URL:news:dk.ed b.internet.webd esign.clientsid e> :) )

        /L
        --
        Lasse Reichstein Nielsen - lrn@hotpop.com
        Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
        'Faith without judgement merely degrades the spirit divine.'

        Comment

        • Lasse Reichstein Nielsen

          #5
          Re: Using setInterval inside an object

          "Daniel" <sorry-no-email@i-get-virus-and-spam.com> writes:
          [color=blue]
          > function myObject() {
          > var o = this;
          > o.intervalcheck = function() { // blahblah }
          > self.setInterva l(o.intervalche ck, 2000);
          > }[/color]

          This looks slightly misleading. It is equivalent to:

          function myObject() {
          var o = this;
          var f = function() { // blahblah };
          o.intervalcheck = f; // seems unused otherwise
          self.setInterva l(f, 2000);
          }

          Functions have several roles in Javascript. They act both as first
          class values (which is what we use when passing a function reference
          to setInterval) and as methods of objects (which is what we do when we
          invoke them as "object.method( )"). However, these two roles are not
          compatible.

          When you write "o.intervalchec k", what you get is the reference to the
          function. There is nothing in this reference that can tell that the
          function has been a method of the "o" object. Calling the function later
          will not make the "this" keyword point to the "o" object.

          If the "//blahblah" uses "this", then it is probably a mistake. If it uses
          "o", then it probably works. In either case, there doesn't seem to be any
          reason for making the function a property of the object.

          (Incidentally, because I just read a book about it, the concept of
          passing an object method as a first class value has been incorporated
          into the C# language. It is called a "delegate", and it works like a
          function while retaining the binding of the "this" keyword. They do
          have an easier time than javascript, since functions aren't first
          class values otherwise.)

          /L
          --
          Lasse Reichstein Nielsen - lrn@hotpop.com
          Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
          'Faith without judgement merely degrades the spirit divine.'

          Comment

          • rh

            #6
            Re: Using setInterval inside an object

            Lasse Reichstein Nielsen <lrn@hotpop.com > wrote in message news:<y8zjv8r9. fsf@hotpop.com> ...[color=blue]
            > "Daniel" <sorry-no-email@i-get-virus-and-spam.com> writes:
            >[color=green]
            > > function myObject() {
            > > var o = this;
            > > o.intervalcheck = function() { // blahblah }
            > > self.setInterva l(o.intervalche ck, 2000);
            > > }[/color]
            >
            > This looks slightly misleading. It is equivalent to:
            >
            > function myObject() {
            > var o = this;
            > var f = function() { // blahblah };
            > o.intervalcheck = f; // seems unused otherwise
            > self.setInterva l(f, 2000);
            > }
            >[/color]

            The two may be functionally equivalent, but the original is preferable
            if a public function is desired. On the other hand a private function
            may be more appropriate, in which case the "o.intervalchec k = f"
            (which provides a public reference to the private function) should be
            removed.

            <snip>
            [color=blue]
            > When you write "o.intervalchec k", what you get is the reference to the
            > function. There is nothing in this reference that can tell that the
            > function has been a method of the "o" object. Calling the function later
            > will not make the "this" keyword point to the "o" object.
            >[/color]

            Agreed there's nothing perhaps in the reference that designates the
            object, but there is something in the de-reference. Otherwise,
            closures in Javascript wouldn't exist.

            It's been noted elsewhere that it seems to be a deficiency in
            Javascript that "this" doesn't refer to the object upon entry to a
            closure. Nonetheless, both private and public properties of the object
            are accessible within the closure. As is the object itself, provided a
            reference to the object has been preserved during object construction
            (e.g., var o = this).
            [color=blue]
            > If the "//blahblah" uses "this", then it is probably a mistake. If it uses
            > "o", then it probably works. In either case, there doesn't seem to be any
            > reason for making the function a property of the object.
            >[/color]

            If it uses "o", then it should do better than "probably works" :-).
            It's reasonable to make the function a property of the object if
            closure is one of the desired effects.

            //rh

            Comment

            • Daniel

              #7
              Re: Using setInterval inside an object

              > When you write "o.intervalchec k", what you get is the reference to the[color=blue]
              > function. There is nothing in this reference that can tell that the
              > function has been a method of the "o" object. Calling the function later
              > will not make the "this" keyword point to the "o" object.[/color]

              I'm a bit confused here as to what you mean... When I've stored the
              reference to "this" in "o", is writing "o" then not equivalent to writing
              "this" in regards to how Javascript interprets the code? So that writing
              "o.intervalchec k" is effectively the same as "this.intervalc heck" in every
              sense but the semantics?
              [color=blue]
              > If the "//blahblah" uses "this", then it is probably a mistake. If it uses
              > "o", then it probably works. In either case, there doesn't seem to be any
              > reason for making the function a property of the object.[/color]

              The //blahblah doesn't use "this". Actually, this whole thing about handling
              scope in Javascript which is rather different, I think, to Actionscript
              which I'm more accustomed to, made me wonder if using "this" inside a method
              of the object would be understood by Javascript as a reference to the method
              and not its object parent. So, assigning the object's "this" to "o"
              comforted me, because I could then stop worrying about what "this" would
              actually be referring to ;) Is this bad programatical style? Won't "o" be
              available to every method under the object?
              [color=blue]
              > (Incidentally, because I just read a book about it, the concept of
              > passing an object method as a first class value has been incorporated
              > into the C# language. It is called a "delegate", and it works like a
              > function while retaining the binding of the "this" keyword. They do
              > have an easier time than javascript, since functions aren't first
              > class values otherwise.)[/color]

              Good to know. I was reading up on first-class values, and read about C's
              functions not being first-class values; I was wondering if that applied to
              C++/C# as well (gonna be doing some of that soon, as I'm starting the
              datamatiker education August 1st ;).

              Thanks,
              Daniel =)


              --
              There are 10 kinds of people: Those who know binary and those who don't.


              Comment

              • Daniel

                #8
                Re: Using setInterval inside an object

                > The two may be functionally equivalent, but the original is preferable[color=blue]
                > if a public function is desired. On the other hand a private function
                > may be more appropriate, in which case the "o.intervalchec k = f"
                > (which provides a public reference to the private function) should be
                > removed.[/color]

                Okay, I think I'm getting what this is about! =) I didn't even think about
                public and private in Javascript (I continue to underestimate what
                Javascript can do, it's been a long walk from "Bah, that's just a simple
                scripting language, can't take more than a couple of weeks to master" to
                here, and the walk continues... ;)
                [color=blue]
                > If it uses "o", then it should do better than "probably works" :-).
                > It's reasonable to make the function a property of the object if
                > closure is one of the desired effects.[/color]

                While closure wasn't something I intentionally aimed for, I don't see any
                problems with it. The object is intended as an autonomous slave horse,
                providing an abstraction layer between Javascript and PHP/MySQL. It is given
                orders to get/update/delete data and return objects and/or statuses. The
                intervalcheck function is supposed to do periodical keepalive stuff like
                pinging the database, error-checking, and maintaining a queue of waiting
                commands. It's not needed as a public method, like "object.interva lcheck()",
                and as I understand, the way I've programmed it here, that won't be possible
                anyway?
                [color=blue]
                > It's been noted elsewhere that it seems to be a deficiency in
                > Javascript that "this" doesn't refer to the object upon entry to a
                > closure. Nonetheless, both private and public properties of the object
                > are accessible within the closure. As is the object itself, provided a
                > reference to the object has been preserved during object construction
                > (e.g., var o = this).[/color]

                This may be a lot to ask, but could you possibly explain this bit to me? Or
                if you had a link that would be nice? This "entry to a closure" concept is
                new to me...

                I'll be reading up on objects in the Bible ;)

                Thanks for your help, RH! =)

                Daniel


                --
                There are 10 kinds of people: Those who know binary and those who don't.


                Comment

                • Daniel

                  #9
                  Re: Using setInterval inside an object

                  > My point being that the use of inner functions carries an overhead and[color=blue]
                  > that makes me think that it would be best to restrict their use to
                  > instances where the fact that they are inner functions, and thus in a
                  > position to form and _exploit_ the resulting closures, has a manifest
                  > advantage.
                  >
                  > Lasse thinks that authoring convenience and ease of maintenance argue
                  > against worrying about this aspect of inner functions to any significant
                  > degree. I am a bit more obsessed with maximising performance. No one
                  > else has expressed an opinion. Knowing the situation you can make up
                  > your own mind about.[/color]

                  In this particular scenario, I will at any time have just one instance of
                  this object in a given document. So regarding the question of inner vs.
                  outer functions, the overhead by using inner functions would only be
                  theoretical, and for some reason I favour nesting code specific to just one
                  object inside the object. Not so much because of programatical reasons, but
                  more because I guess it "fits" better with the way my head understands it
                  (at least for the moment being ;)

                  As for the potential problem with circular references you describe, I'll
                  definitely have to take this into account. Your post was very informative,
                  and I probably wouldn't have realized this issue existed had it not been for
                  you, so thank you _very_ much for taking the time to write such an in-depth
                  reply! =)

                  Regards,
                  Daniel


                  --
                  There are 10 kinds of people: Those who know binary and those who don't.


                  Comment

                  • Daniel

                    #10
                    Re: Using setInterval inside an object


                    "Lasse Reichstein Nielsen" <lrn@hotpop.com > wrote in message
                    news:8yriv5w6.f sf@hotpop.com.. .[color=blue]
                    > It depends. If called as a method, "this" refers to the object for
                    > which the function is a method. If called as a function reference,
                    > "this" refers to the global object (which is stupid design, but that's
                    > a different story).[/color]

                    I definitely agree =) The way the "this" keyword is used in Javascript has
                    caused me quite a lot of confusion, it doesn't always make sense the way
                    it's used - sometimes it seems like things have been "patched up" to do some
                    kind of workaround that doesn't make programatical sense. Like when you
                    reference a form from within an element in the form using "this.form" - that
                    doesn't make sense, since that *should* indicate a form nested in the
                    element. I haven't seen the ECMA specs, but in Actionscript the equivalent
                    reference would have been "this._pare nt" which makes much more sense, both
                    logical and programatical (plus, it makes no assumption about what type of
                    object the parent is).
                    [color=blue]
                    > It is not bad style to assign the value of "this" to a local variable
                    > to be able to capture it in closures. It is a well known way of doing
                    > exactly that.[/color]

                    Great =)
                    [color=blue]
                    > Congratulatons :)[/color]

                    Actually, anyone with a B level in math and a highschool diploma gets in,
                    so... But thanks! =) Hehe ;)

                    Thanks to you, RH, and Richard, I'm beginning to get a really good
                    understanding of this. You guys rock! The time and effort you're spending
                    here really means a lot to me (and others!) =)

                    Thanks,
                    Daniel

                    PS: Jeg har kigget lidt på din side - den der random art-dippedut er helt
                    vildt cool =)

                    --
                    There are 10 kinds of people: Those who know binary and those who don't.


                    Comment

                    • Daniel

                      #11
                      Re: Using setInterval inside an object


                      "Lasse Reichstein Nielsen" <lrn@hotpop.com > wrote in message
                      news:k7b2tp7b.f sf@hotpop.com.. .[color=blue]
                      > It does make some sense. Each form element has a reference to the form
                      > it is inside. The "onclick" handler is a function and a method of the
                      > element (or rather the DOM node corresponding to it) that it is on, so
                      > when it is called, they "this" keyword points to the form element.[/color]

                      OOOHH!!! It's just the way I've been reading it! I've read it as, literally,
                      a part of a path, when really the ".form" is a property of the object
                      referenced by "this" (an object, which in turn can be extended with
                      "paths" - properties - to address another object). ".form" could just as
                      well contain a reference the top document, giving us a whole different
                      scenario. And "_parent" in Actionscript is just a property as well. A path
                      is really nothing but a series of objects linked together, and that linkage
                      can be arbitrary, not necessarily hierarchical. Come to think of it, the
                      concept of hierarchy itself is a perception... I think I just had a small
                      wake-up call :P

                      Thanks! =)

                      Daniel


                      --
                      There are 10 kinds of people: Those who know binary and those who don't.


                      Comment

                      • Richard Cornford

                        #12
                        Re: Using setInterval inside an object

                        "Daniel" <sorry-no-email@i-get-virus-and-spam.com> wrote in message
                        news:3f017100$0 $97169$edfadb0f @dread12.news.t ele.dk...
                        <snip>[color=blue]
                        >... , and for some reason I favour nesting code specific to just
                        >one object inside the object. Not so much because of programatical
                        >reasons, but more because I guess it "fits" better with the way my
                        >head understands it (at least for the moment being ;)[/color]

                        There are many patterns for creating JavaScript object classes, looking
                        around Douglas Crockford's site (and following some of the links from
                        there) will expose several approaches.

                        I like the idea of grouping all code related to an object into one
                        structure in a way similar to Java. It is still feasible to do that with
                        JavaScript without creating a unique function object for each method of
                        each object instance.

                        The following executes a function expression as the file loads, that
                        function call returns a function that will act as a class constructor.
                        The resulting closure acts as a repository for private static members
                        but it can also server to group the code for the entire class into one
                        function body. However, because this constructor returning function is
                        only called once any inner functions assigned to the prototype of the
                        constructor will be shared by all instances of the class and that gives
                        you the clear object code structure while not creating more function
                        objects than is needed.


                        var MyObject = function(){
                        var counter = 0; //private static (class) member

                        function incrementCounte r(){ //private static (class) method.
                        return counter++;
                        };

                        function constructor(id) { //class constructor.
                        this.id = id;
                        var self = this;

                        //call private static (class) method and assign the returned
                        //index to a private instance member.
                        var index = incrementCounte r();

                        this.getIndex = function(){ //privileged instance method.
                        return index;
                        };
                        };

                        //privileged static (class) method (a property of the constructor)
                        constructor.get NoOfInsts = function(){
                        return counter;
                        };

                        //public instance method that is also privileged at the class
                        //level. It has no access to the closure formed when
                        //constructing new objects. The one function object is
                        //shared by all instances of the class as it has been assigned
                        //to the prototype of the constructor function.
                        constructor.pro totype.getId = function(){
                        return this.id;
                        }

                        return constructor; //return the constructor.
                        }(); //simultaneously define and call (one-off)!

                        var test = new MyObject('anyId ');

                        There is no need, but it also remains possible to extend the prototype
                        after the constructor has been returned from the one-off function
                        call.:-

                        MyObject.pubSta tic = "anything" //public static (class) member

                        MyObject.protot ype.pubInstVar = 8; //public instance member

                        Richard.

                        --

                        Example JavaScript DOM listings for: Opera 7.11,
                        Mozilla 1.2 and ICEbrowser 5.4
                        <URL: http://www.litotes.demon.co.uk/dom_root.html >


                        Comment

                        • Daniel

                          #13
                          Re: Using setInterval inside an object


                          "Daniel" <sorry-no-email@i-get-virus-and-spam.com> wrote in message
                          news:3f019b7d$0 $97230$edfadb0f @dread12.news.t ele.dk...[color=blue]
                          > PS: In case of the "read a book" reply, which one should I get?[/color]

                          I'm gonna order the Javascript Definitive Guide as Douglas suggests on
                          Amazon, so that's that question answered ;)


                          Comment

                          • Richard Cornford

                            #14
                            Re: Using setInterval inside an object

                            "Daniel" <sorry-no-email@i-get-virus-and-spam.com> wrote in message
                            news:3f019b7d$0 $97230$edfadb0f @dread12.news.t ele.dk...
                            <snip>[color=blue][color=green]
                            >> var MyObject = function(){[/color]
                            > ...[color=green]
                            >> }(); //simultaneously define and call (one-off)!
                            >>
                            >> var test = new MyObject('anyId ');[/color]
                            >
                            >This is really a brainteaser for me... I partially understand the
                            >one-off concept here in that I can see how the "space"
                            >MyObject owns[*] in the variable declaration becomes an
                            >object constructor[/color]

                            The constructor (the inner function with the identifier "constructo r")
                            is returned by the in-line execution of its outer function and a
                            reference to that inner function is assigned to the MyObject variable.
                            Thus the MyObject global variable becomes a reference to a function that
                            is an inner function of the closure formed by executing its outer
                            function in-line once, but that function can be used as a constructor
                            (that is actually true of all functions, though most of the time using a
                            random function as an object constructor would be pointless) and it has
                            already had an instance method assigned to its prototype.

                            The primary purpose of the inline execution of the outer function is to
                            provide a closure to contain private static (class) members. Variables
                            and functions local to the closure but also available to any other
                            function defined within the same closure. Which includes the constructor
                            and the closure formed when new objects of the class are created, their
                            privileged and private methods and their non-privileged public members.
                            However, the function expression that is executed in-line also serves as
                            an enclosing structure for the entire class definition. Resulting in a
                            more Java-like class definition.
                            [color=blue]
                            >that is immediately fired, and then assigns "test" an instance of that
                            >object (which as I understand it, isn't really a "MyObject" instance,
                            >but rather a "constructo r" instance...[/color]

                            " A rose by any other name . ". If you execute - var myArray = Array; -
                            and then call - new myArray(); - the constructor called is the Array
                            function object. myArray only holds a reference to that function object,
                            but the global Array property also only holds a reference to that
                            function object. A genuine working Array object is the end result.

                            It is a MyObject instance because - if(test instanceof MyObject) - will
                            compare the reference to the function object that constructed - test -
                            with the with the function object referred to by the global MyObject
                            property. The identifier "constructo r" is out of scope outside the
                            closure formed by executing its outer function in-line.
                            [color=blue]
                            >[*] This is my brain's way of expressing how expressions evaluate to
                            > something else, like "now = theCurrentTime( )" >>> theCurrentTime( )'s[/color]
                            "space"[color=blue]
                            > in that expression is replaced with whatever's returned by the[/color]
                            function. I[color=blue]
                            > know it would be sufficient to just say "evaluate", but since I don't
                            > understand this, I thought it would be a good idea to try to explain[/color]
                            how my[color=blue]
                            > failing brain understands this term ;)
                            >
                            > What exactly the MyObject function then is, I don't quite understand.[/color]

                            It is a mechanism to form a closure with the constructor function of a
                            class.
                            [color=blue]
                            >As it is not itself instantiated,
                            >it can't see it anywhere existing as an object,[/color]

                            The closure formed when its inner function is returned implies the
                            preservation of at least the "variable" object from the execution
                            context of the outer function but the whole process is anonymous and
                            externally inaccessible (else how could the variables and function
                            definitions within the closure that represent private static members be
                            private?).
                            [color=blue]
                            > actually I can't see how the counter inside will keep its value
                            >from one object construction to another, since it - in itself - is
                            >just a function?[/color]

                            The outer function is executed once and once only. The function -
                            function incrementCounte r(){ - is an inner function of that outer
                            function, as is the - constructor - function, they have equal status.
                            Object instances are constructed by a call to the - constructor -
                            function, via the reference to it that was returned by the in-line
                            execution of the outer function and assigned to the MyObject variable.
                            The execution of one inner function does not impact upon the existence
                            of another inner function within the same closure ( well it could, but
                            in this case (and most cases) it doesn't).
                            [color=blue]
                            > And why is it only called once?[/color]

                            Because a class only needs one constructor function object and only one
                            closure to act as a repository for its private static members.
                            [color=blue]
                            >As I see it it will be called every time you
                            > do a "new MyObject()"...[/color]

                            The outer function is not called, it can never be called again because
                            there are not references to it left outside of the closure that was
                            formed when it was executed once. The outer function returned a
                            reference to its inner 'constructor' function and it is that function
                            that is invoked each time - new MyObject(); - is called.
                            [color=blue]
                            >Ofcourse it must be because I don't fully understand objects
                            >(or functions) in Javascript but the Bible's explanations are
                            >REALLY tame. (OT, I think I need to buy a better book - any
                            > suggestions?)[/color]

                            JavaScript books are always a problem, many are out of date and most are
                            primarily concerned with scripting the browser DOM and don't go into the
                            more esoteric aspects of functions, closures or objects.

                            When I was first learning JavaScript "Javascript the Definitive Guide"
                            (then it its second edition) was the most useful book I had, but for its
                            DOM reference rather than its language coverage (which is still much
                            better than the other JavaScript books I have seen).

                            You will be lucky to find any reference to Douglas Crockford's
                            application of closures to provide JavaScript objects with private
                            instance members, or my application of his technique at the constructor
                            level to provide JavaScript classes with private static members. I even
                            have JavaScript books that assert that JavaScript objects cannot have
                            private members (of any type).

                            Incidentally, avoid books about JavaScritp 2. The next revision of the
                            ECMA Script language has not been finalised yet so anything about
                            JavaScript 2 is speculation based on proposals and one or two reference
                            implementations . It won't be practical for client-side use for at least
                            4 years anyway.
                            [color=blue]
                            > Or is the answer in the "new MyObject('anyId ')" assignment?[/color]

                            No, that is the totally standard construction of a JavaScript object.
                            [color=blue]
                            > As I understand your code, it's a function that, when executed,
                            >returns an object constructer that is also executed, all the while
                            >keeping track of a counter (in a way I don't understand).[/color]

                            That "is also executed" worries me. The constructor that is returned is
                            only executed when - new MyObject() - is used. In my code the function
                            that is executed in-line is the outer function and its return value (the
                            constructor reference) is assigned to the variable MyObject.
                            [color=blue]
                            > Argh, I know it must be like dancing with an elephant to help
                            >me here, so I'll definitely understand if you just tell me to go
                            >read a book ;)[/color]

                            If I knew a book that would help I might [1] but this dance is more fun
                            than the "will you pleeeeeeeeease show us the ****** script" dance that
                            half the other posters insist on starting with.

                            Richard.

                            [1] If you feel like reading a book anyway, have your read "Godel,
                            Echer, Bach: an Eternal Golden Braid" by Douglas R. Hofstadter yet?


                            Comment

                            • Daniel

                              #15
                              Re: Using setInterval inside an object

                              I think I get it now... [This is how I get it:] At the time of declaring
                              "var MyObject = function(){..." , scriptly speaking (hey, nice phrase ;), the
                              function is just a function like any other function. The fact that it
                              contains a constructor and that it's gonna "morph" to functionally "become"
                              this constructor is yet unknown, since at this time all the function does is
                              occupy memory.

                              Then, we have the first (and last) execution of *that particular* function
                              when we (if we read it literally (and I still do that a lot ;)) try to
                              instantiate it *as if it were* an object constructor. Javascript says, "you
                              want an instance of that object?" and checks to see what "that object" is,
                              i.e. the function is evaluated. The function starts its work and ends up
                              returning its inner constructor function, but not just that, because if it
                              did, you'd end up using the "new" keyword on an object constructor
                              *function* object, and not an object *constructor*. No, it uses that one-off
                              thingie to evaluate the function object to become the object constructor, so
                              that the assignment argument becomes valid, and the "test" var becomes an
                              instance of what the MyObject is *now*, which is the object constructor
                              inside the function is was before. I actually understand it as if the
                              constructor inside "MyObject" effectively hijacks the variable name and
                              reference to "MyObject", cutting its connection to the public while
                              retaining access to its properties and methods for its own members (the
                              closure).

                              Now, at every new MyObject instantiation, using "new" on "MyObject" doesn't
                              execute the orginial function (that reference is lost), but reaches straight
                              inside it to the object constructor class that provides all its instances
                              with access to its outer function's resources. (And it can keep track of the
                              counter since incrementCounte r is now an outer function to itself :)

                              Did I get it? =)

                              On a side note, since English isn't exactly my mother tongue, and although I
                              believe I'm better at it than many of my fellow Danes (well, maybe not Lasse
                              , but others ;), I do have a tendency to mix up words and phrases, and
                              sometimes simply talk nonsense (also in the text above, I'm sure). Of course
                              it doesn't help either that I'm learning a programming language through a
                              foreign language (I mean, phrases like "The primary purpose of the inline
                              execution of the outer function is to provide a closure to contain private
                              static (class) members" I have to read a few times before they sink in,
                              hehe). I apologize for when this results in having to repeat and rephrase
                              things to me that should be clear the first time, and when it makes me seem
                              even more daft than I am ;)

                              That said, I have never understood objects better than I do right now! =)

                              Thank you, Richard! For your time, your patience, your links, and book tips
                              =)

                              Daniel

                              PS:[color=blue]
                              > If you feel like reading a book anyway, have your read "Godel,
                              > Echer, Bach: an Eternal Golden Braid" by Douglas R. Hofstadter yet?[/color]
                              No, I haven't, and I don't even know what it is... I'll check it out on
                              amazon, see if it looks interesting to me :) Thanks!


                              --
                              There are 10 kinds of people: Those who know binary and those who don't.


                              Comment

                              Working...