1
function Person(name) {
    this.name = name;
    return this;
}

var someone = new Person('someone');
console.log(someone.name);

var someoneelse = Person('someoneelse');
console.log(someoneelse.name);

It this a good pattern to implement constructor functions (classes). This works fine with both new and without new.

[Update:] I think I got the answer I was looking for. Using this without 'new' would return a global object and a very bad idea (Thanks to the comment by Vohuman "by Without using new, this in the constructor is the global object not an instance of the constructor")

[More Update:] Doing it the right way to take care of new and without new,

function Person(name) {
   if (this instanceof Person) {
      this.name = name;
   }
   else {
      return new Person(name);
   }
};
scriptuser
  • 55
  • 2
  • 9

2 Answers2

2

You don't use this if you're not going to use the new operator. Instead create a local object, like so:

function Person(name) {
    var obj = {}
    obj.name = name;
    return obj;
}

var someoneelse = Person('someoneelse');
console.log(someoneelse.name);

This is called a factory function, and I prefer it to using new. To each their own, though.

Here's a good article on all of this.

jmealy
  • 583
  • 1
  • 5
  • 14
  • 2
    The second use is not a factory function; it's broken. For a factory function you will need to define your own object and return it. –  Jul 10 '16 at 02:02
  • Fixed my wording, @torazaburo. Thank you for noting. – jmealy Jul 10 '16 at 02:04
  • 1
    You generally use the [factory pattern](https://en.wikipedia.org/wiki/Factory_method_pattern) if there are more than one category of sub-classes or specialized properties. Where the parameter would be used to specify the exact class, which isn't happening in this case. – Spencer Wieczorek Jul 10 '16 at 02:18
0

The keyword 'new' helps to prevent the pollution on global namespace so if you don't want to type new everytime you do this you can have he following code:

function Person(name) {
   if(this===window){
     return new Person(name);
   }
   this.name = name;
   return this;
}
Shrikantha Budya
  • 646
  • 1
  • 4
  • 15
  • 2
    I would rather use the following (works in node environment as well), function Person(firstname, lastname) { if (this instanceof Person) { this.firstname = firstname; this.lastname = lastname; } else { return new Person(firstname, lastname); } }; – scriptuser Jul 10 '16 at 05:17