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.

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top