-1

I'm sure that I'm missing something but I don't understand why developers so often create new instances of Functions. For example I see this basic concept in numerous tutorials.

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

var myCar = new Car("Toyota", "Tacoma", 1997);
console.log(myCar.make +" " +myCar.model +" " +myCar.year);

But if functions can be reused as many times as needed why create new instances?

This function appears to do the same thing and I can use it as many times as needed.

function Car(make, model, year) {
    console.log(make +" " +model +" " +year);
}

car("Toyota", "Tacoma", 1997);
car("Honda", "Civic", 2005);
// etc etc...
DR01D
  • 1,325
  • 15
  • 32
  • 4
    Because sometimes you want to create objects. Sure, in your code that only logs some values and does nothing else, they're not necessary. – Bergi Jun 28 '17 at 16:01
  • 2
    I realize that you likely asked the question in good faith, but this is almost certain to draw a @#!tstorm of conflicting opinions and semi-useless factoids like how V8 optimizes object creation with `new`. The short, short answer is that constructor functions are *never* necessary and *sometimes* convenient. – Jared Smith Jun 28 '17 at 16:02
  • 2
    This is Javascript's original implementation of a class. It just happens to use a function for the constructor. It's a class instantiation vs a vanilla function call. – Andy Ray Jun 28 '17 at 16:04
  • @NickWyman I'd say more [this one](https://stackoverflow.com/questions/8698726/constructor-function-vs-factory-functions) – Jared Smith Jun 28 '17 at 16:06
  • 1
    Are the downvotes really necessary? I VTC'd as dupe but its edge-casey. And it's a totally legit question and if you haven't been a JS dev then you probably don't know it's everyone's favorite dead horse to beat. – Jared Smith Jun 28 '17 at 16:08

2 Answers2

0

Using the new keyword allows you to create instances of objects that you can then manipulate.

In your first example, you can change the model of the car (for instance) after you've created it with myCar.model = "Carrera".

Aurélien Gasser
  • 3,043
  • 1
  • 20
  • 25
0

By saying new Car the keyword new does three things: 1. Create a new object instance such as BobsCar.model("..."); 2. Assign its prototype to the function’s .prototype | BobsCar.prototype.etc... 3. Apply the function with the object instance set as “this” | this.make = make;