Loading ...
Sorry, an error occurred while loading the content.

Re: new function ()

Expand Messages
  • Douglas Crockford
    ... The object will always have the new function s prototype in its inheritance chain, which will be linked to the function. Every time you make another foo,
    Message 1 of 3 , Jun 2, 2009
    • 0 Attachment
      --- In jslint_com@yahoogroups.com, "pauanyu" <pcxunlimited@...> wrote:
      >
      > I am curious why JSLint dislikes this:
      >
      > var foo = new function () {
      > this.bar = 1;
      > }();
      >
      > Without the "new", "this" is bound to the global object. It is true that this is a rather odd form that I doubt is seen very often, nonetheless I don't see anything inherently wrong with it.
      >
      > Mind explaining?

      The object will always have the new function's prototype in its
      inheritance chain, which will be linked to the function. Every
      time you make another foo, you are going to make another function
      object and prototype object, and prevent them from being garbage
      collected.

      There's no point to that, particularly when you have better forms like

      var foo = (function () {
      return {
      bar: 1;
      };
      }());

      or even better

      var foo = {
      bar: 1
      };
    • pauanyu
      ... Ah, so it has to do with more efficient memory management. I continue to be amazed how powerful the return {} construct is. At any rate, thanks for
      Message 2 of 3 , Jun 2, 2009
      • 0 Attachment
        --- In jslint_com@yahoogroups.com, "Douglas Crockford" <douglas@...> wrote:
        >
        > The object will always have the new function's prototype in its
        > inheritance chain, which will be linked to the function. Every
        > time you make another foo, you are going to make another function
        > object and prototype object, and prevent them from being garbage
        > collected.
        >
        > There's no point to that, particularly when you have better forms like
        >
        > var foo = (function () {
        > return {
        > bar: 1;
        > };
        > }());
        >
        > or even better
        >
        > var foo = {
        > bar: 1
        > };
        >

        Ah, so it has to do with more efficient memory management. I continue to be amazed how powerful the "return {}" construct is. At any rate, thanks for explaining.
      Your message has been successfully submitted and would be delivered to recipients shortly.