0

from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

Making sure that this points to the right thing regardless of how the object is instantiated can be difficult. However, there is a simple idiom to make this easier.

var Person = function(firstName) {
  if (this instanceof Person) {
    this.firstName = firstName;
  } else {
    return new Person(firstName);
  }
}

Why are we returning new Person?

How can the else case actually occur?

Toskan
  • 13,911
  • 14
  • 95
  • 185
  • 1
    near duplicate of [When should I automatically create an object even if `new` is forgotten?](http://stackoverflow.com/q/20859985/1048572) – Bergi Mar 16 '16 at 06:49

2 Answers2

2

The Person is just a regular function. The difference makes how it is invoked:

1) It can be invoked as a constructor

 var p = new Person('Bill Gates');

The this context in the constructor is an instance of the Person. this instanceof Person evaluates to true.
The newly created object is automatically returned when invoking the function as a constructor.

2) Invoked as a regular function

var p = Person('Bill Gates');

this is the Window object or undefined in strict mode. this instanceof Person evaluates to false.
However to still receive an object on simple invocation, new Person(firstName) is called manually to return the correct object.

Check more details in this post.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
  • further down on the linked page you will find: "// Define the Student constructor". Now we could call `Student("Bill Gates", "Coding")` without the `new`... wouldn't that return us a person instead of a student? – Toskan Mar 16 '16 at 06:55
  • @Toskan Without new `Student("Bill Gates", "Coding")` will just return `undefined`. – Dmitri Pavlutin Mar 16 '16 at 06:59
0

There is no requirement that your "class" function Person gets called with the new operator.

If it does, the value of this inside the function will be an instance of the Person class.

If it doesn't, as in var p = Person('Toskan'), then the value of this will be the global object, and the prototype won't be set correctly to the Person.prototype object. To get around that, the function explicitly returns the result of calling the function with the new keyword.

GregL
  • 37,147
  • 8
  • 62
  • 67