And
And

Reputation: 37

Can a constructor function also be called a function expression?

Is the only difference between them that an expression has some kind of logic inside it, while a constructor function only has a list of properties? I'm confused why there are separate names for seemingly the same thing..

 //this is an expression
 var myFunctionExpression = function(){console.log('hi')};

 //this is a constructor
 var myConstructorFunction = function(term){this.greeting = term;}

Upvotes: 1

Views: 319

Answers (1)

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

Is the only difference between them that an expression has some kind of logic inside it, while a constructor function only has a list of properties?

Not really.

The function expression:

var foo = function() { ... }

and the function statement:

function foo() {
   ...
}

are two different ways to define functions.

The constructor function is a special kind of functions that is supposed to create new instances of objects with the new operator. Inside this function you can use this to access to the instance it creates. Also, the function set its prototype as the prototype of the newly created instance.

A constructor function can be declared with a function expression

var Foo = function(whatever) {
   this.whatever = whatever;
} 

var f = new Foo(1);
// f.whatever = 1

or a function statement:

function Foo(whatever) {
   this.whatever = 1;
}

var f = new Foo();
// f.whatever = 1

Note however, that the constructor function doesn't necessarily set any properties (which contradicts yours a constructor function only has a list of properties) - this would be a perfectly valid constructor function:

  function Foo() {}
  var f = new Foo();

While this trivial example doesn't make much sense, introducing a prototype shows the real value:

  function Foo() {}
  Foo.prototype.bar = function() {}

  var f1 = new Foo();
  var f2 = new Foo();

  // both f1 and f2 have Foo.prototype as their prototype
  // both can call .bar() then

Upvotes: 2

Related Questions