0

I have seen 2 syntax for javascript prototype : first is from tutorial http://www.w3schools.com/js/js_object_prototypes.asp second is generated by typescript http://www.typescriptlang.org/Playground

What's the advantage of second syntax over first simpler and traditional constructor syntax ?

https://jsfiddle.net/v6gxe7wc/1/

    function Person1(first, last) {
    this.firstName = first;
    this.lastName = last;
}

var Person2 = (function () {

  function Person2(first, last) {

    this.firstName = first;
    this.lastName = last;
  }

  return Person2;
})();

var person1 = new Person1("John", "Doe");
var person2 = new Person2("John", "Doe");
user310291
  • 36,946
  • 82
  • 271
  • 487

1 Answers1

2

JavaScript is case-sensitive. If you look at this line:

var person1 = new person1("John", "Doe");

...you have new person1, but there is no identifier named person1. There is, however, a Person1:

var person1 = new Person1("John", "Doe");

The second syntax, by the way, offers no advantages as is. Where it would be advantageous is if you had additional variables used by the constructor that you don't want to expose:

var Person2 = (function () {

  var defaultFirstName = 'John';
  var defaultLastName = 'Doe';

  function Person2(first, last) {

    this.firstName = first || defaultFirstName;
    this.lastName = last || defaultLastName;
  }

  return Person2;
})();

In this case, for example, defaultFirstName and defaultLastName are hidden from everything but the constructor.

Jacob
  • 77,566
  • 24
  • 149
  • 228