Building an object with constructor function


I created a new object with a function, but when i console.log the object i get an undefined. why?

this is my new object:

    var car = function() {
  this.wheels = 4;
  this.engines = 1;
  this.seats = 5;

returns undefined

Hey Tomer-n,

You have to instantiate the object. For example add var tesla = new car(); and then console.log(tesla);


To expand, car.wheels is undefined because the object doesn’t exist until it’s instantiated.

Yes, car is not an object, it is a function and car.wheels has no meaning. Do as Doug says.

thanks Doug! can I add a property who has a space in it? like
this.“last name” = “tomer”;

Object properties with spaces in them can be referred to with bracket notation:

this["last name"] = "tomer";
1 Like

A constructor function is a function which returns an object when we use the new keyword. The this keyword does not refer to the function, but to this new object which is returned.

const Car = function(wheels) {
	this.wheels = wheels;
const car =  new Car(4);
console.log(car); // {wheels: 4}

In ES6, we can use classes to do the same thing:

class Horse {
	constructor(legs) {
		this.legs = legs;
const horse = new Horse(4); 
console.log(horse); // {legs: 4}

In both cases, it is standard to use Titlecase for the Constructor / Class, and lowercase for the instance.

1 Like