문제

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