0

I have seen two ways of creating instances:

Method 1

function Contact(first, last) {
this.firstName = first;
this.lastName = last;
this.fullName = function() {
    return this.firstName + " " + this.lastName;
    };
}

Method 2

var Associate = function(first, last) {
this.firstName = first;
this.lastName = last;
this.fullName = function() {
    return this.firstName + " " + this.lastName;
    };
};

Are there any benefits of the first over the other?

What is the correct terminology for these? I believe they are supposed to be called "Object Constructor Functions" but I have also seen them called classes.

Kos
  • 70,399
  • 25
  • 169
  • 233
Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Philipp Gayret Feb 06 '14 at 15:17
  • Yes, this is a duplicate question and should be closed. – Greg Gum Feb 06 '14 at 15:19

2 Answers2

1

Method 1 is a function definition, while method 2 is a function expression that is assigned to a variable. Both end up doing the similar thing, but with differences:

  • the sequence of events is different (see: hoisting)
  • method 2 doesn't set the name parameter of the function

Regarding the terminology - "constructor function" is a common term for these:

var foo = new Contact();
console.log(foo.constructor === Contact) // true

Technically there is nothing special about this functions though. The convention is to capitalise functions that are intended to use as constructors.

Kos
  • 70,399
  • 25
  • 169
  • 233
-1

Both Method 1 and Method 2 are syntactically correct but Method 1 is like standard when you want to create class in Javascript.

Method 1 give better readability.

Method 2 is good for function variables when you need to pass functions to other parts of the program.