Building an object with constructor function

Building an object with constructor function
0

#1

hello

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;
};
  console.log(car.wheels); 

returns undefined


#2

Hey Tomer-n,

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

Doug


#3

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


#4

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


#5

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


#6

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

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

#7

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.