object.property = new function(){

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • emailscotta@gmail.com

    #1

    object.property = new function(){

    Some of the object properties in the Dojo Toolkit are set to objects
    but they are using syntax like this:

    object.property = new function() {
    this.property = someValue;
    this.property = someFunction;
    }

    Is the property set to a new object and if so what is the "new
    function()" statment doing?

    Thanks,

    Scott

  • Lasse Reichstein Nielsen

    #2
    Re: object.property = new function(){

    emailscotta@gma il.com writes:
    object.property = new function() {
    this.property = someValue;
    this.property = someFunction;
    }
    >
    Is the property set to a new object and if so what is the "new
    function()" statment doing?
    The "function ..." is simply a function expression, so the above
    is equivalent to:
    ---
    var Temp = function() {
    this.property = someValue;
    this.property = someFunction;
    }
    object.property = new Temp
    ---
    where "new Temp" is the same as "new Temp()".

    So, yes, object.property is assigned a new object as value,
    and that object is initialized using the following function.
    If the anonymous initializer function is as simple as in this
    example, it would be simpler to use an object literal, i.e.,

    object.property = { property:someVa lue, property2:someF unction };

    Even for more elaborate computations, you can do them first and
    then create an object literal from the resulting values.

    Compared to using "new" on an anonymous function, the object literal
    approach does not create a prototype object referring to the anonymous
    function, so it would be more memory efficient, but probably not
    as readable

    /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

    • Richard Cornford

      #3
      Re: object.property = new function(){

      emailscotta@gma il.com wrote:
      Some of the object properties in the Dojo Toolkit are set
      to objects but they are using syntax like this:
      >
      object.property = new function() {
      this.property = someValue;
      this.property = someFunction;
      }
      >
      Is the property set to a new object and if so what is
      the "new function()" statment doing?
      The (right side) operand of the - new - operator is expected to evaluate
      as a reference to a function object, and that function object is used to
      construct a new object that is the result of the - new - expression (an
      arguments list is optional with the - new - operator and omitted here).

      The the right of the new operator is a function _Expression_, which is
      evaluated when executed and results in a function object being created,
      with the value of the function expression being a reference to that new
      (anonymous, in this case) function object.

      The two together are a completely legal way of creating a single unique
      object, but completely pointless (particularly in terms of the needless
      complexity of the expression). When a function is used as a constructor
      its use allows for the inheritance of methods/properties from a
      prototype, but here no such inheritance is possible because there is no
      method of accessing the prototype of the anonymous function object (it
      goes out of scope as soon as the assignment expression is finished).

      A simpler alternative would be:-

      object.property = {
      property:someVa lue,
      property2:someF unction
      };

      - and the effect would be the same (but probably much more efficiently).

      I would question the depth of understanding of javascript possessed by
      someone who wrote your original version in preference to the above
      (Which doesn't bode well for the Dojo Toolkit). However, there may be
      closure-based code within the real (anonymous) constructor functions
      which may justify their use.

      Richard.


      Comment

      • emailscotta@gmail.com

        #4
        Re: object.property = new function(){


        Richard Cornford wrote:
        emailscotta@gma il.com wrote:
        Some of the object properties in the Dojo Toolkit are set
        to objects but they are using syntax like this:

        object.property = new function() {
        this.property = someValue;
        this.property = someFunction;
        }

        Is the property set to a new object and if so what is
        the "new function()" statment doing?
        >
        The (right side) operand of the - new - operator is expected to evaluate
        as a reference to a function object, and that function object is used to
        construct a new object that is the result of the - new - expression (an
        arguments list is optional with the - new - operator and omitted here).
        >
        The the right of the new operator is a function _Expression_, which is
        evaluated when executed and results in a function object being created,
        with the value of the function expression being a reference to that new
        (anonymous, in this case) function object.
        >
        The two together are a completely legal way of creating a single unique
        object, but completely pointless (particularly in terms of the needless
        complexity of the expression). When a function is used as a constructor
        its use allows for the inheritance of methods/properties from a
        prototype, but here no such inheritance is possible because there is no
        method of accessing the prototype of the anonymous function object (it
        goes out of scope as soon as the assignment expression is finished).
        >
        A simpler alternative would be:-
        >
        object.property = {
        property:someVa lue,
        property2:someF unction
        };
        >
        - and the effect would be the same (but probably much more efficiently).
        >
        I would question the depth of understanding of javascript possessed by
        someone who wrote your original version in preference to the above
        (Which doesn't bode well for the Dojo Toolkit). However, there may be
        closure-based code within the real (anonymous) constructor functions
        which may justify their use.
        >
        Richard.

        Here is the actual code from the toolkit (which I hope is not a problem
        since it's open source). So if I understand correctly sampleTransport
        becomes a new object but instead of using an object literal they used
        the "new function()" statement. Is there a benefit to doing this?

        /*
        dojo.io.sampleT ranport = new function(){
        this.canHandle = function(kwArgs ){
        // canHandle just tells dojo.io.bind() if this is a good transport to
        // use for the particular type of request.
        if(
        (
        (kwArgs["mimetype"] == "text/plain") ||
        (kwArgs["mimetype"] == "text/html") ||
        (kwArgs["mimetype"] == "text/javascript")
        )&&(
        (kwArgs["method"] == "get") ||
        ( (kwArgs["method"] == "post") && (!kwArgs["formNode"]) )
        )
        ){
        return true;
        }

        return false;
        }

        this.bind = function(kwArgs ){
        var hdlrObj = {};

        // set up a handler object
        for(var x=0; x<dojo.io.hdlrF uncNames.length ; x++){
        var fn = dojo.io.hdlrFun cNames[x];
        if(typeof kwArgs.handler == "object"){
        if(typeof kwArgs.handler[fn] == "function") {
        hdlrObj[fn] = kwArgs.handler[fn]||kwArgs.handle r["handle"];
        }
        }else if(typeof kwArgs[fn] == "function") {
        hdlrObj[fn] = kwArgs[fn];
        }else{
        hdlrObj[fn] = kwArgs["handle"]||function(){};
        }
        }

        // build a handler function that calls back to the handler obj
        var hdlrFunc = function(evt){
        if(evt.type == "onload"){
        hdlrObj.load("l oad", evt.data, evt);
        }else if(evt.type == "onerr"){
        var errObj = new dojo.io.Error(" sampleTransport Error: "+evt.msg);
        hdlrObj.error(" error", errObj);
        }
        }

        // the sample transport would attach the hdlrFunc() when sending the
        // request down the pipe at this point
        var tgtURL = kwArgs.url+"?"+ dojo.io.argsFro mMap(kwArgs.con tent);
        // sampleTransport .sendRequest(tg tURL, hdlrFunc);
        }

        dojo.io.transpo rts.addTranspor t("sampleTranpo rt");
        }
        */

        Comment

        • emailscotta@gmail.com

          #5
          Re: object.property = new function(){


          Lasse Reichstein Nielsen wrote:
          emailscotta@gma il.com writes:
          >
          object.property = new function() {
          this.property = someValue;
          this.property = someFunction;
          }

          Is the property set to a new object and if so what is the "new
          function()" statment doing?
          >
          The "function ..." is simply a function expression, so the above
          is equivalent to:
          ---
          var Temp = function() {
          this.property = someValue;
          this.property = someFunction;
          }
          object.property = new Temp
          ---
          where "new Temp" is the same as "new Temp()".
          >
          So, yes, object.property is assigned a new object as value,
          and that object is initialized using the following function.
          If the anonymous initializer function is as simple as in this
          example, it would be simpler to use an object literal, i.e.,
          >
          object.property = { property:someVa lue, property2:someF unction };
          >
          Even for more elaborate computations, you can do them first and
          then create an object literal from the resulting values.
          >
          Compared to using "new" on an anonymous function, the object literal
          approach does not create a prototype object referring to the anonymous
          function, so it would be more memory efficient, but probably not
          as readable
          >
          /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.'

          So is this essense an anonymous constructor function?

          Comment

          • Lasse Reichstein Nielsen

            #6
            Re: object.property = new function(){

            "Richard Cornford" <Richard@litote s.demon.co.ukwr ites:

            [ object.property = new function(){...} ]
            When a function is used as a constructor its use allows for the
            inheritance of methods/properties from a prototype, but here no such
            inheritance is possible because there is no method of accessing the
            prototype of the anonymous function object (it goes out of scope as
            soon as the assignment expression is finished).
            Actually, and probably unintended, it is available, as:
            object.property .constructor.pr ototype

            That leaves both the function and its prototype hanging around for
            no good reason.

            /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

            • Michael Winter

              #7
              Re: object.property = new function(){

              On 11/08/2006 02:01, emailscotta@gma il.com wrote:
              Richard Cornford wrote:
              [snip]
              >I would question the depth of understanding of javascript possessed
              >by someone who wrote your original version in preference to the
              >above (Which doesn't bode well for the Dojo Toolkit). However,
              >there may be closure-based code within the real (anonymous)
              >constructor functions which may justify their use.
              >
              So if I understand correctly sampleTransport becomes a new object but
              instead of using an object literal they used the "new function()"
              statement.
              That's correct.
              Is there a benefit to doing this?
              As Richard noted, the latter approach is useful in closure-based code
              where the execution context formed by the function expression becomes
              the basis for that closure. However, this is not the case for the code
              you posted: the canHandle and bind properties could have been added
              within an object literal, and the addTransport method call could have
              been made at any point after the object was assigned to the
              sampleTranport [sic] property.

              There are two other issues, both within the bind method:
              }else{
              hdlrObj[fn] = kwArgs["handle"]||function(){};
              This assignment statement is executed within a loop. Whenever the
              function expression here is evaluated (if the handle property of kwArgs,
              type-converted to Boolean, evaluates to false), a new function object
              will be created with its [[scope]] property containing the entire
              execution context stack. Needless to say, this is quite pointless for a
              function that, when called, does nothing. It would have been better to
              define a dummy function elsewhere and assign a reference to that, thus
              adding less overhead.
              var hdlrFunc = function(evt){
              The second issue is much simpler: why the above isn't simply a function
              declaration, I don't know. Unless the bind method errors out, the above
              will always be evaluated, and the time of evaluation is irrelevant in
              this instance. I think the authors were getting a little carried away,
              using function expressions just for the hell of it.

              Mike


              By the way, please don't post code containing tabs: they wrap far too
              easily. Use a couple of spaces per level instead.

              Comment

              • Lasse Reichstein Nielsen

                #8
                Re: object.property = new function(){

                emailscotta@gma il.com writes:
                Here is the actual code from the toolkit (which I hope is not a problem
                since it's open source). So if I understand correctly sampleTransport
                becomes a new object but instead of using an object literal they used
                the "new function()" statement. Is there a benefit to doing this?
                In this particular case, none.

                Generally, probably none too. If you do not need the extra layer of a
                prototype for the constructed object, there is no reason to create
                it.

                /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

                • Richard Cornford

                  #9
                  Re: object.property = new function(){

                  emailscotta@gma il.com wrote:
                  Richard Cornford wrote:
                  <snip>
                  >I would question the depth of understanding of javascript
                  >possessed by someone who wrote your original version in
                  >preference to the above (Which doesn't bode well for the
                  >Dojo Toolkit). However, there may be closure-based code
                  >within the real (anonymous) constructor functions which
                  >may justify their use.
                  >
                  Here is the actual code from the toolkit (which I hope is not
                  a problem since it's open source). So if I understand
                  correctly sampleTransport becomes a new object but instead
                  of using an object literal they used the "new function()"
                  statement. Is there a benefit to doing this?
                  >
                  /*
                  dojo.io.sampleT ranport = new function(){
                  this.canHandle = function(kwArgs ){
                  <snip>
                  }
                  this.bind = function(kwArgs ){
                  <snip>
                  }
                  >
                  dojo.io.transpo rts.addTranspor t("sampleTranpo rt");
                  This is the only line of code that actually gets executed as a
                  consequence of calling the anonymous function object as a constructor.
                  }
                  */
                  There does not appear to be any reason in this code for not using an
                  object literal:-

                  dojo.io.sampleT ranport = {
                  canHandle:funct ion(kwArgs){
                  ...
                  },
                  bind:function(k wArgs){
                  ...
                  }
                  };
                  dojo.io.transpo rts.addTranspor t("sampleTranpo rt");

                  - as the closures formed at the constructor level in the original are
                  not (and so represent another avoidable overhead).

                  Richard.



                  Comment

                  • Richard Cornford

                    #10
                    Re: object.property = new function(){

                    Lasse Reichstein Nielsen wrote:
                    "Richard Cornford" <Richard@litote s.demon.co.ukwr ites:
                    >
                    [ object.property = new function(){...} ]
                    >
                    >When a function is used as a constructor its use allows for
                    >the inheritance of methods/properties from a prototype, but
                    >here no such inheritance is possible because there is no
                    >method of accessing the prototype of the anonymous function
                    >object (it goes out of scope as soon as the assignment
                    >expression is finished).
                    >
                    Actually, and probably unintended, it is available, as:
                    object.property .constructor.pr ototype
                    >
                    That leaves both the function and its prototype hanging
                    around for no good reason.
                    That must be the second or third time that construct has slipped my
                    mind, probably because it is far too convoluted to ever consider using
                    it.

                    Richard.


                    Comment

                    • Douglas Crockford

                      #11
                      Re: object.property = new function(){

                      emailscotta@gma il.com wrote:
                      Some of the object properties in the Dojo Toolkit are set to objects
                      but they are using syntax like this:
                      >
                      object.property = new function() {
                      this.property = someValue;
                      this.property = someFunction;
                      }
                      >
                      Is the property set to a new object and if so what is the "new
                      function()" statment doing?
                      I don't like this use of new. I don't like implied invocations; I think that all
                      invocations should use the () suffix. Without it, people like Scott will be
                      confused. It also sets up an anonymous function as a constructor, which is weird
                      and a little wasteful.

                      I would rather see something like

                      object.property = function () {
                      ...
                      return {
                      property: ...,
                      };
                      }();

                      This still allows the methods to be privileged.


                      Comment

                      • emailscotta@gmail.com

                        #12
                        Re: object.property = new function(){


                        Douglas Crockford wrote:
                        emailscotta@gma il.com wrote:
                        Some of the object properties in the Dojo Toolkit are set to objects
                        but they are using syntax like this:

                        object.property = new function() {
                        this.property = someValue;
                        this.property = someFunction;
                        }

                        Is the property set to a new object and if so what is the "new
                        function()" statment doing?
                        >
                        I don't like this use of new. I don't like implied invocations; I think that all
                        invocations should use the () suffix. Without it, people like Scott will be
                        confused. It also sets up an anonymous function as a constructor, which is weird
                        and a little wasteful.
                        >
                        I would rather see something like
                        >
                        object.property = function () {
                        ...
                        return {
                        property: ...,
                        };
                        }();
                        >
                        This still allows the methods to be privileged.
                        >
                        http://javascript.crockford.com/
                        Thanks for the response. I have actually checked out you website before
                        and it's great. Hopefuly this is not bad edicate but I can send you an
                        email with a more eleborate example from Yahoo's API? I would really
                        like to get a good grasp of these concepts?

                        Thanks,

                        Scott

                        Comment

                        • mikewse@hotmail.com

                          #13
                          Re: object.property = new function(){

                          I would rather see something like
                          >
                          object.property = function () {
                          ...
                          Yes, that makes a lot of sense I think.
                          Browsing through this issue on google, I came across this discussion
                          between some dojo developers:


                          One of them seem to be advocating a pattern like
                          var o = new function(){ ... }();
                          which looks like a mix-up of the two solutions discussed here. Or is
                          there a good motivation for using both "new" and "()" ?

                          Best regards
                          Mike

                          Comment

                          • mikewse@hotmail.com

                            #14
                            Re: object.property = new function(){

                            Oh, after actually thinking I realized that
                            var o = new function(){ ... };
                            and
                            var o = new function(){ ... }();
                            are equivalent.

                            Just like Lasse pointed out with named constructors earlier in the
                            thread:
                            var o = new Temp;
                            var o = new Temp();

                            Best regards
                            Mike

                            Comment

                            • Douglas Crockford

                              #15
                              Re: object.property = new function(){

                              mikewse@hotmail .com wrote:
                              Oh, after actually thinking I realized that
                              var o = new function () { ... };
                              and
                              var o = new function () { ... }();
                              are equivalent.
                              So are

                              var o = new function () { ... }();

                              and

                              var o = function () { ... }();

                              except that the form with new creates a useless level of indirection.
                              There is no excuse for using new function.


                              Comment

                              Working...