Blog>
Snippets

Using 'this' in a Constructor Function

Use 'this' in a constructor function to create properties for the instances of an object.
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

// Creating a new instance of Car
var myCar = new Car('Toyota', 'Corolla', 2001);
This JavaScript code defines a constructor function 'Car' that creates an object with 'make', 'model', and 'year' properties using 'this'. Then it creates a new instance 'myCar' with specific values.
<!DOCTYPE html>
<html>
<head>
<style>
.car-info{font-family: Arial, sans-serif;}
</style>
</head>
<body>

<div id="demo" class="car-info"></div>

<script>
  // Assuming Car constructor function is already defined.
  document.getElementById('demo').innerHTML = 'My car is a ' + myCar.make + ' ' + myCar.model + ' from ' + myCar.year + '.';
</script>

</body>
</html>
This HTML includes a style for displaying car information and a script that uses the previously created 'myCar' instance to display its properties in the web page.