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

Re: [jslint] Re: ES5 and constructors

Expand Messages
  • Stefan Weiss
    ... The error is not caused by calling the constructor itself, but by the attempt to use the this value as an object inside the constructor. In ES3, the
    Message 1 of 7 , Nov 9, 2010
    • 0 Attachment
      Mark Volkmann wrote:
      > But I read that invoking a constructor in ES5 without using the "new"
      > keyword is an error. If that is true then there must be some way to
      > distinguish between constructor functions and non-constructor functions. If
      > the case of the first letter is how it is done, then it is more than just a
      > convention in ES5.

      The error is not caused by calling the constructor itself, but by the
      attempt to use the "this value" as an object inside the constructor. In
      ES3, the "this value" would be coerced to the global object, but in ES5
      strict mode, that's no longer the case.

      That doesn't mean that it's possible to look at a function and tell if
      it's intended to be used as a constructor. For example, the function

      function foo() {}

      could be used as a constructor

      var bar = new foo();

      or not

      var bar = foo();

      To make the purpose of the function more obvious, we use the
      uppercase/lowercase convention. It's just a convention, though, not a
      syntactic requirement.


      stefan
    • Morgaut Alexandre Louis Marc
      A good exemple var s = String(3); // typeof s === string var s = new String(3); // typeof s === object String() can be used to convert any value into a
      Message 2 of 7 , Nov 9, 2010
      • 0 Attachment
        A good exemple

        var s = String(3); // typeof s === "string"

        var s = new String(3); // typeof s === "object"

        String() can be used to convert any value into a string while new String() will create an object which constructor is String and which toString method will return its conversion into a string value.

        In ES5 strict mode, without new, when not applied as a method on an object, the value of this can null or undefined

        You can never say for sure that a function won't be used as a constructor

        You just have some little tricks like...
        - the function has been called once with new (then you are quite sure)
        - a property has been defined on its prototype (useless on other function than constructors)
        - its first letter is upper case (convention only)
        - it has a JSDoc with the tag "@constructor" (the developers probably wants you to manage it as a constructor)
        - it is a standard builtin constructor (from JS Core, DOM, BOM, ...)

        >



        [Non-text portions of this message have been removed]
      Your message has been successfully submitted and would be delivered to recipients shortly.